What purpose does the Comparer
class serve if the type that you specify already implements IComparable
?
If I specify Comparer.Defaul
If a type implements IComparable
, it is almost certainly better to use that than IComparable
. With value types, the performance of IComparable
is often much better than that of the non-generic IComparable
. With inheritable reference types, IComparable
can offer better semantics than IComparable
by allowing rankings based upon derived-type fields.
For an example of the latter benefit, suppose one has an abstract base class ScheduleEvent
, with a property EventTime
, that implements IComparable
by sorting EventTime
. Derived types include ScheduledPopupMessageEvent
with a message string, a ScheduledGongEvent
with a GongVolume
parameter. Multiple ScheduleEvent
s with the same EventTime
must report zero for IComparable
, because there is no safe and consistent way to rank ScheduleEvent
s of different types, and because two ScheduleEvent
s which both report themselves as unranked relative to a third must, for consistency, report themselves as unranked relative to each other. On the other hand, there would be no problem with having ScheduledGongEvent
implementing IComparable
take GongVolume
into account as well as EventTime
, or with ScheduledPopupMessageEvent
doing likewise with its Message parameter.
It is useful, then, to have things like sorting routines use IComparable
if it exists, but be able to fall back to IComparable
if IComparable
does not exist. Checking for whether a class implements IComparable
and selecting an appropriate implementation if it does, however, is a little expensive. Fortunately, once a type is determined to have an IComparable
implementation, it can be relied upon to always have one; likewise, if a type is found not to have such an implementation, it never will. Further, if a generic class has any static fields, every combination of type parameters will yield a different class with different fields. Thus, the first time Comparer
is run with a particular type parameter T, it will store the Comparer routine it returns into a static field. If Comparer
is run again with that same type, it will return the same comparer routine. Although it might seem odd to have a static Comparer
class with just one method, creating a separate Comparer
class for every type T
provides a place to store the created compare routine.