What's the difference between IComparable & IEquatable interfaces?
Both the interfaces seem to compare objects for equality, so what are the major differences between them?
IEquatable
tests whether two objects are equal.
IComparable
imposes a total ordering on the objects being compared.
For example, IEquatable
would tell you that 5 is not equal to 7. IComparable
would tell you that 5 comes before 7.
IEquatable<T>
for equality.
IComparable<T>
for ordering.
In addition to Greg D's answer:
You might implement IComparable
without implementing IEquatable
for a class where a partial ordering makes sense, and where you very definitely want the consumer to infer that just because CompareTo()
returns zero, this does not imply that the objects are equal (for anything other than sorting purposes).
As stated on the MSDN Page for IEquatable:
The IComparable interface defines the
CompareTo
method, which determines the sort order of instances of the implementing type. The IEquatable interface defines theEquals
method, which determines the equality of instances of the implementing type.
Equals
vs. CompareTo