What purpose does the Comparer
class serve if the type that you specify already implements IComparable
?
If I specify Comparer.Defaul
I think your question is why have a base class that only seems to have one useful method which happens to be the same method you'd implement if you implemented the interface directly. If I understood that correctly I guess you're right that there's not much benefit to deriving from Comparer
as opposed to implementing IComparer
directly except that the base class provides you with a generic and non-generic implementation with a single overridden method.
But if your question is why have both IComparer
and IComparable
, then
as others have indicated, Comparer
allows you to define different ways to perform the comparison. It is an implementation of the Strategy design pattern. A great example of this would be the various StringComparer
properties such as StringComparer.Ordinal, StringComparer.OrdinalIgnoreCase, etc. This allows you to sort strings differently under different circumstances which the IComparable
interface simply cannot anticipate.
But in addition to being able to re-define the way a comparison is performed, sometimes providing an external comparer is the only way you can do it. For example, the Windows Forms ListView class allows you to specify an IComparer for its sort logic. But ListViewItem does not implement IComparable. So without a comparer strategy that knows how to do it, ListViewItem is not sortable because it has no default IComparable implementation.
So at the end of the day, it's just another extensibility point that allows you more flexibility when you're not the author of the type that is to be sorted (or you need multiple sorting strategies.)
Perhaps an example would help. Let's say you're writing an extension method that checks to see if a given value is between a range.
public static bool Between(this T value, T minValue, T maxValue) {
var comparer = Comparer.Default;
int c1 = comparer.Compare(value, minValue);
int c2 = comparer.Compare(value, maxValue);
return (c1 >= 0 && c2 <= 0);
}
In this case, I don't know anything about the type T. It may implement IComparable
or it may implement IComparable
or it may implement neither and an exception will be thrown. This also allows me to easily add an overload for this method that lets the caller pass in their own comparer. But Comparer comes in handy here because it lets me get a default comparer for an unknown type that may or may not implement a generic or non-generic IComparable interface.