Identifying the Default Comparers for a Type
When creating methods that perform comparison or sort operations, it is usual to allow callers to use a default comparer, a standard .NET comparers or a custom class. For generic methods, it is essential to be able to obtain a default comparer for a type.
A number of operations provided by .NET framework classes use comparers that implement the IComparer<T> or IEqualityComparer<T> interface. These interfaces are used by classes that compare two values, either to determine which appears first when ordered or to check if two values are considered equal. Most of the methods provided include several overloaded versions. One version will permit comparisons to be made with a specific comparer object, provided via an argument. Another will not require this parameter, instead using the default comparer for the types being tested.
When you are writing similar methods you may also decide to include a version with a default comparer and one where a specific comparer can be supplied. To prevent repetition of code, it is likely that the version that uses the default comparer will instantiate such an object and use it as an argument in a call to the more complex version of the method. If you are creating generic methods, you may not know in advance what types will need to be compared, making it impossible to select a default comparer by name. In these cases, you can request the default comparers using functionality provided by the .NET framework.
Obtaining a default Comparer for a type is a simple operation that uses a static member of the Comparer<T> class. Simply retrieve the value of the Default property. For example, the following line of code creates a default comparer for integers:
Comparer<int> comparer = Comparer<int>.Default;
When you need a default EqualityComparer, you can use the Default property from the EqualityComparer<T> class in a similar manner. The following code creates a default EqualityComparer for integers:
EqualityComparer<int> equalityComparer = EqualityComparer<int>.Default;
26 June 2012