If i want to compare objects and they implement the IEquatable<> interface, i have a few questions:
- Why do i have to override Equals(object ) if i have to implements Equals<>
- can i use == and != once i implement IEquatable ?
If i want to compare objects and they implement the IEquatable<> interface, i have a few questions:
Regarding #1:
From MSDN:
If you implement
IEquatable<T>
, you should also override the base class implementations ofObject::Equals(Object)
andGetHashCode()
so that their behavior is consistent with that of theIEquatable<T>::Equals
method. If you do overrideObject::Equals(Object)
, your overridden implementation is also called in calls to the staticEquals(System.Object, System.Object)
method on your class. This ensures that all invocations of theEquals()
method return consistent results.
2) No, these do plain reference comparisons and do not use the Equals method.
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.