For the code below
public struct Person
{
public int ID;
public static bool operator ==(Person a, Person b) { return a.Equals(b); }
public static bool operator !=(Person a, Person b) { return !a.Equals(b); }
}
Why does the compiler give me these warnings?
What's wrong with not defining the methods below?
warning CS0660: 'Person' defines operator == or operator != but
does not override Object.Equals(object o)
warning CS0661: 'Person' defines operator == or operator != but
does not override Object.GetHashCode()
EDIT: This answer has been corrected, among other things to note that user-defined value types don't generate
==
, and to mention the performance issues withValueType.Equals
.In general, overridding one, but not all, is confusing. The user expects neither to be overridden, or both to be, with the same semantics.
Microsoft's recommendations for this state (among other things):
In your case, you have a valid reason to defer to
Equals
(the compiler doesn't automatically implement==
) and override only those two (==
/!=
). However, there's still a performance issue, sinceValueType.Equals
uses reflection:Thus, it's still recommended to override all (
==
/!=
/Equals
) in the end. Of course, performance may not matter for this trivial struct.