SYSK 158: IComparable<T> vs. IEquatable<T>


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 >=.

 


 

Comments (3)

  1. A Visual Studio 2005 code snippet that implements a skeleton value type adhering the Framework Design Guidelines.

  2. I posted an article on why it is important to override the Object.Equals method when implementing the IEquatable interface on codeproject (http://www.codeproject.com/useritems/IEquatable.asp).