What purpose does the Comparer
class serve if the type that you specify already implements IComparable
?
If I specify Comparer.Defaul
The type doesn't need to implement IComparable, it can be any type - there are no constrains on T
:
public abstract class Comparer : IComparer, IComparer
The new Comparer
you create implements IComparer
and the non-generic IComparer
, and can be used for comparisons and sorting of collections.
You are correct: if your type, Customer
implements IComparable
, and you don't need another comparison, Comparer
isn't useful to you. Most classes in the .net framework can accept both IComparable
or Comparer
, so you can use either one.
However, you are wrong to assume that is always the case. It is very possible to create a Comparer
for a non-Comparable type. Note that the following is not required:
public abstract class Comparer : IComparer, IComparer
where T : IComparable, IComparable
Suppose you have a simple class, Person
and you want to sort a list of Persons
, your best bet it to write a Comparer:
public class Person
{
string Name { get; set; }
}