views:

633

answers:

4

Hi folks, both the interfaces seem to compare objects for equality, so what's the major differences between them?

TIA

+32  A: 

IEquatable tests whether two objects are equal.

IComparable imposes an 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.

Greg D
+1. Good explanation.
shahkalpesh
A: 

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 the Equals method, which determines the equality of instances of the implementing type.

Equals vs. CompareTo

Will Eddins
+3  A: 

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 very definitely you wish the consumer to draw the inference that just because CompareTo() returns zero, this does not imply that the objects are equal (for anything other than sorting purposes).

Damien_The_Unbeliever
+1 for interesting point.
Greg D
That sounds much more like a special-case comparer than like an object implementing `IComparable` properly. Can you come up with a meaningful example where `CompareTo(…) == 0` does **not** imply equality? I certainly can’t. In fact, the interface contract (as per MSDN) **requires** that `CompareTo(…) == 0` implies equality. To put it bluntly, in such a case as yours, use a special `Comparator` object, do *not* implement `IComparable`.
Konrad Rudolph
@Konrad - I did indicate several caveats - that the type doesn't implement IEquatable (so obviously, the originator doesn't want to include an equality test), and that CompareTo results are used for sorting, *not* to evaluate equality. You also get into questions of which equality is relevant (reference, value, ignoring "arbitrary" attributes - a blue book of 500 pages in length may be "equal" to a red book of 500 pages in length, for the purposes of IComparable)
Damien_The_Unbeliever
Your last sentence is wrong, and this is the particular mistake I wanted to point out: `IComparable` is wholly inappropriate here. What you’ve got is a very *particular* ordering that only applies in one special situation. For such situations, implementing a general `IComparable` is wrong. This is what `IComparer`s are there for. For example, people cannot be ordered meaningfully. But they *can* be ordered according to their salary, their shoe size, the number of their freckles or their weight. Hence, we would implement different `IComparer`s for all these cases.
Konrad Rudolph
+1  A: 

IEquatable<T> for equality.

IComparable<T> for ordering.

Islam Ibrahim