There are three ways to map objects of some reference type T
:
- Using the
object.Equals
- With implementation of
IEquatable<T>.Equals
(only for types that implement IEquatable<T>
) - With comparison operator
==
In addition, for each of these cases, there are two possibilities:
- Static type of compared objects
T
(or some other base T
) - Static type of compared objects
Rules you definitely need to know:
- By default for
Equals
and operator==
it is necessary to check the reference equality Equals
implementations will work correctly no matter what static type of compared objectsIEquatable<T>.Equals
should always behave the same as object.Equals
, but if the static type of objects is T
, it will offer slightly better performance.
So what does all this mean in practice?
Generally, you should use Equals
to check for equality (overriding object.Equals
as needed) and implement IEquatable<T>
to provide slightly better performance. In this case, object.Equals
should be implemented in terms of IEquatable<T>.Equals
.
For some specific types (for example, System.String
) it is also acceptable to use operator==
, although you should be careful not to make "polymorphic comparisons." Equals
methods, on the other hand, will work correctly even if you make such comparisons.
You can see an example of polymorphic comparison and why this might be a problem here .
Finally, never forget that if you override object.Equals
, you must also override object.GetHashCode
.
Jon
source share