When I implement objects that I want to compare using the IEquatable<T>
interface:
- Why do I have to override
Equals(object)
method if I already implementedEquals(T)
? - Can I use
==
and!=
operators once I implementIEquatable<T>
?
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>
?
1) As Ray said, override
Equals(object)
to ensure consistency when the method is called from classes which don't know (statically) that you implementIEquatable<T>
. For instance, the non-generic collections classes will useEquals(object)
for comparisons. You should also overrideGetHashCode()
.2) Implementing
IEquatable<T>
doesn't overload the == and != operators automatically, but there's nothing to stop you from doing so, just likeSystem.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.From MS Docs article on
IEquatable<T>
:No, operators do not use the Equals method. They must be overloaded separately to do so.