C
C#2y ago
hanu

What's the meaning of CS0659?

'class' overrides Object.Equals(object o) but does not override Object.GetHashCode()
'class' overrides Object.Equals(object o) but does not override Object.GetHashCode()
I got this warning message but i cannot find what's the reason I should override GetHashCode. Also, how should I implement it?
15 Replies
TheRanger
TheRanger2y ago
ur trying to make a class that implements the IEqualityComparer interface right?
hanu
hanu2y ago
uhm wait
internal readonly struct Vector3D
{
public double X { get; init; }
public double Y { get; init; }
public double Z { get; init; }

public override bool Equals([NotNullWhen(true)] object? obj)
{
if (obj is Vector3D vector)
{
return X == vector.X && Y == vector.Y && Z == vector.Z;
}
return false;
}
}
internal readonly struct Vector3D
{
public double X { get; init; }
public double Y { get; init; }
public double Z { get; init; }

public override bool Equals([NotNullWhen(true)] object? obj)
{
if (obj is Vector3D vector)
{
return X == vector.X && Y == vector.Y && Z == vector.Z;
}
return false;
}
}
this is how it now looks like
TheRanger
TheRanger2y ago
i copy pasted ur code, it does not give me ur error u sure the error is not somewhere else? anyway you can just override GetHashCode like you override any method
hanu
hanu2y ago
bigthonk
hanu
hanu2y ago
i'm on .net 6
TheRanger
TheRanger2y ago
so it does implement the IEquatable interface
hanu
hanu2y ago
does this matter? uh yeah i just added it to see if it solves the problem
hanu
hanu2y ago
yeah it says "An override of Equals implies that you also want to override GetHashCode." but idk why
Klarth
Klarth2y ago
It's to ensure correct, consistent behavior when using both equals and getting a hash. eg. for Dictionary and HashSet. You can override GetHashCode and use https://learn.microsoft.com/en-us/dotnet/api/system.hashcode.combine?view=net-7.0 which is good enough. You probably shouldn't be creating your own vector type though.
hanu
hanu2y ago
okay got it thanks uh wait so the 'correct, consistent behavior' means 'two hash codes are equal if and only if Equals() == true'?
Klarth
Klarth2y ago
It means that the equals and hash code calculation should both rely on the exact same subset of properties. Imagine if your Equals uses X and Y, but your hash code uses X, Y, and Z.
hanu
hanu2y ago
i got it what would be a great alternative rather than manually implementing a vector type? Vector3?
Klarth
Klarth2y ago
Depends on what you're trying to accomplish, perf requirements, what libraries you are or can use, etc.
hanu
hanu2y ago
reasonable thanks all, anyways!
Want results from more Discord servers?
Add your server
More Posts