I’m following examples Apress pro c# framework and I have question on IComparer interface
If I want to create some custom comparer which will compare my objects by name I should implement IComparer interface so I have following
public class CarNameComparer : IComparer
{
int IComparer.Compare(object obj1, object obj2)
{
Car temp1 = obj1 as Car;
Car temp2 = obj2 as Car;
if (temp1 != null && temp2 != null)
{
return String.Compare(temp1.Name, temp2.Name);
}
else
{
throw new ArgumentException("Parameter is not a Car");
}
}
}
And I’m calling to compare like this
Array.Sort(italianCars, new CarNameComparer());
Which is fine, but this approach is comparing only two instances, as far as I can see this is a limited usage. What if I want to compare bunch of objects, not just two of them ?
You’re misunderstanding the use of the Comparer. It will still sort the array even if there are a thousand instances of
Car. It just does it by comparing two at a time!