C
C#3y 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
TheRanger3y ago
ur trying to make a class that implements the IEqualityComparer interface right?
hanu
hanuOP3y 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
TheRanger3y 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
hanuOP3y ago
bigthonk
hanu
hanuOP3y ago
i'm on .net 6
TheRanger
TheRanger3y ago
so it does implement the IEquatable interface
hanu
hanuOP3y ago
does this matter? uh yeah i just added it to see if it solves the problem
hanu
hanuOP3y ago
yeah it says "An override of Equals implies that you also want to override GetHashCode." but idk why
Klarth
Klarth3y 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
hanuOP3y 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
Klarth3y 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
hanuOP3y ago
i got it what would be a great alternative rather than manually implementing a vector type? Vector3?
Klarth
Klarth3y ago
Depends on what you're trying to accomplish, perf requirements, what libraries you are or can use, etc.
hanu
hanuOP3y ago
reasonable thanks all, anyways!
Want results from more Discord servers?
Add your server