Welcome to MSDN Blogs Sign in | Join | Help

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

 

 

Published Tuesday, July 18, 2006 5:34 AM by irenak

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# SYSK 158: IComparable&lt;T&gt; vs. IEquatable&lt;T&gt; &raquo; Wagalulu - Microsoft &raquo; &raquo; SYSK 158: IComparable&lt;T&gt; vs. IEquatable&lt;T&gt;

# Sortable Value Type Code Snippet

Tuesday, July 18, 2006 10:37 AM by Peter Ritchie's MVP Blog
A Visual Studio 2005 code snippet that implements a skeleton value type adhering the Framework Design Guidelines.

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

Sunday, September 23, 2007 6:36 AM by Geert Verhoeven

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

Leave a Comment

(required) 
required 
(required) 
 
Page view tracker