How to best implement Equals for custom types?
There is a whole set of guidelines on MSDN as well. You should read them well, it is both tricky and important.
A few points I found most helpful:
Value Types don't have Identity, so in a
struct Point
you will usually do a member by member compare.Reference Types usually do have identity, and therefore the Equals test usually stops at ReferenceEquals (the default, no need to override). But there are exceptions, like string and your
class Point2
, where an object has no useful identity and then you override the Equality members to provide your own semantics. In that situation, follow the guidelines to get through the null and other-type cases first.And there are good reasons to keep
GethashCode()
andoperator==
in sync as well.
In the one that takes an obj, if the type of obj is Point2, call the type specific Equals. Inside the type specific Equals, make sure that all the members have the same value.
public override bool Equals ( object obj )
{
return Equals(obj as Point2);
}
public bool Equals ( Point2 obj )
{
return obj != null && obj.X == this.X && obj.Y == this.Y ...
// Or whatever you think qualifies as the objects being equal.
}
You probably ought to override GetHashCode as well to make sure that objects that are "equal" have the same hash code.