SYSK 158: IComparable vs. IEquatable
Both compare objects of types T… So, which should your objects implement?
IComparable<T> specifies ordering, e.g. less than, equals, greater than. String class implements IComparable<T> interface with its int CompareTo(T objectToCompare) function. IEquatable<T> only tells you weather the objects are the equal or not via the bool Equals(T objectToCompare) function.
Below are the “rules of thumb” I follow:
- Always implement IEquatable<T> interface for value types to avoid unnecessary boxing/unboxing of Object.Equals.
- When implementing IEquatable<T>, also override Object.Equals. After all, you want Equals to mean the same thing regardless of invocation method…
- When providing custom implementation of equality, either by implementing IEquatable<T> or by overriding Object.Equals, also implement operator== and operator!=.
- When implementing IComparable<T>, also implement IEquatable<T>
- When implementing IComparable<T>, also implement operators <, >, <=, and >=.