When I implement objects that I want to compare using the IEquatable<T>
interface:
Equals(object)
method if I already implemented Equals(T)
?==
and !=
operators once I implement IEquatable<T>
?IEquatable<T> lets a structure implement a strongly typed Equals method so no boxing is required. Thus much better performance when using value types with generic collections. Reference types don't benefit as much but the IEquatable<T> implementation does let you avoid a cast from System.
From the MSDN: The IEquatable(T) interface is used by generic collection objects such as Dictionary(TKey, TValue) , List(T) , and LinkedList(T) when testing for equality in such methods as Contains , IndexOf , LastIndexOf , and Remove .
A value type overriding Equals method indicates that it supports comparing two instances of the type for value equality. Consider implementing the IEquatable<T> interface to support strongly typed tests for equality. This ensures that callers performing equality checks invoke the strongly typed System.
Just take the above example, int implements the IEquatable<int>. Likewise, the other primitive types also implement IEquatable<T>. Generally, IEquatable<T> is very useful for the value types.
From MS Docs article on IEquatable<T>
:
If you implement
IEquatable<T>
, you should also override the base class implementations ofEquals(Object)
andGetHashCode()
so that their behavior is consistent with that of theEquals(T)
method. If you do overrideEquals(Object)
, your overridden implementation is also called in calls to the staticEquals(Object, Object)
method on your class. In addition, you should overload theop_Equality
andop_Inequality
operators. This ensures that all tests for equality return consistent 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 when the method is called from classes which don't know (statically) that you implement IEquatable<T>
. For instance, the non-generic collections classes will use Equals(object)
for comparisons. You should also override GetHashCode()
.
2) Implementing IEquatable<T>
doesn't overload the == and != operators automatically, but there's nothing to stop you from doing so, just like System.String
does. You should document this very clearly if you do, however - and be careful when you make comparisons between other types of reference (e.g. MyType and Object) which will still use the identity comparison. I suspect it's not a great idea to do this unless it's going to be a very heavily used type in your code, where everyone will become very familiar with it and where the syntactic sugar of overloading == will really make a positive impact on readability.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With