[ACCEPTED]-Understanding IEquatable-iequatable
From MS Docs article on
IEquatable<T>
:If you implement
IEquatable<T>
, you should also 9 override the base class implementations 8 ofEquals(Object)
andGetHashCode()
so that their behavior is consistent 7 with that of theEquals(T)
method. If you do 6 overrideEquals(Object)
, your overridden implementation 5 is also called in calls to the staticEquals(Object, Object)
method 4 on your class. In addition, you should 3 overload theop_Equality
andop_Inequality
operators. This ensures 2 that all tests for equality return consistent 1 results.No, operators do not use the Equals method. They must be overloaded separately to do so.
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
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.