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 >=.
Comments
- Anonymous
July 18, 2006
PingBack from http://microsoft.wagalulu.com/2006/07/18/sysk-158-icomparablet-vs-iequatablet/ - Anonymous
July 18, 2006
A Visual Studio 2005 code snippet that implements a skeleton value type adhering the Framework Design Guidelines. - Anonymous
September 22, 2007
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).