[ACCEPTED]-Understanding IEquatable-iequatable

Accepted answer
Score: 53
  1. From MS Docs article on IEquatable<T>:

    If you implement IEquatable<T>, you should also 9 override the base class implementations 8 of Equals(Object) and GetHashCode() so that their behavior is consistent 7 with that of the Equals(T) method. If you do 6 override Equals(Object), your overridden implementation 5 is also called in calls to the static Equals(Object, Object) method 4 on your class. In addition, you should 3 overload the op_Equality and op_Inequality operators. This ensures 2 that all tests for equality return consistent 1 results.

  2. No, operators do not use the Equals method. They must be overloaded separately to do so.

Score: 43

1) As Ray said, override Equals(object) to ensure consistency 18 when the method is called from classes which 17 don't know (statically) that you implement 16 IEquatable<T>. For instance, the non-generic collections 15 classes will use Equals(object) for comparisons. You should 14 also override GetHashCode().

2) Implementing IEquatable<T> doesn't 13 overload the == and != operators automatically, but 12 there's nothing to stop you from doing so, just 11 like System.String does. You should document this very 10 clearly if you do, however - and be careful 9 when you make comparisons between other 8 types of reference (e.g. MyType and Object) which 7 will still use the identity comparison. I 6 suspect it's not a great idea to do this 5 unless it's going to be a very heavily used 4 type in your code, where everyone will become 3 very familiar with it and where the syntactic 2 sugar of overloading == will really make 1 a positive impact on readability.

More Related questions