There are three ways objects of some reference type T can be compared to each other:
- With the
object.Equals method
- With an implementation of
IEquatable<T>.Equals (only for types that implement IEquatable<T>)
- With the comparison operator
==
Furthermore, there are two possibilities for each of these cases:
- The static type of the objects being compared is
T (or some other base of T)
- The static type of the objects being compared is
object
The rules you absolutely need to know are:
- The default for both
Equals and operator== is to test for reference equality
- Implementations of
Equals will work correctly no matter what the static type of the objects being compared is
IEquatable<T>.Equals should always behave the same as object.Equals, but if the static type of the objects is T it will offer slightly better performance
So what does all of this mean in practice?
As a rule of thumb you should use Equals to check for equality (overriding object.Equals as necessary) and implement IEquatable<T> as well to provide slightly better performance. In this case object.Equals should be implemented in terms of IEquatable<T>.Equals.
For some specific types (such as System.String) it's also acceptable to use operator==, although you have to be careful not to make "polymorphic comparisons". The Equals methods, on the other hand, will work correctly even if you do make such comparisons.
You can see an example of polymorphic comparison and why it can be a problem here.
Finally, never forget that if you override object.Equals you must also override object.GetHashCode accordingly.