BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

.NET Framework
.NET 2.0+

Implementing IComparer<T>

The generic IComparer<T> interface was introduced with the .NET framework version 2.0. It is used to compare two values to determine which is the larger. The interface is used in many standard .NET methods, particularly those that sort information.

Testing the Comparers

We can now test the two comparers by creating several Customer objects and comparing them. The code below creates three customers and adds them to an array. The array is sorted using an AnnualSpendComparer. The results are therefore ordered by the annual spend value, as seen in the comment.

Customer customer1 = new Customer();
customer1.Forename = "Jim";
customer1.Surname = "Smith";
customer1.AnnualSpend = 1000;

Customer customer2 = new Customer();
customer2.Forename = "Bob";
customer2.Surname = "Smith";
customer2.AnnualSpend = 2000;

Customer customer3 = new Customer();
customer3.Forename = "Bob";
customer3.Surname = "Jones";
customer3.AnnualSpend = 1500;

Customer[] customers = new Customer[] { customer1, customer2, customer3 };
Array.Sort(customers, new AnnualSpendComparer());

/* RESULTS

Jim Smith, £1000
Bob Jones, £1500
Bob Smith, £2000

*/

Try changing the comparer to a NameComparer to see the Customers ordered by surname and forename.

Array.Sort(customers, new NameComparer());

/* RESULTS

Bob Jones, £1500
Bob Smith, £2000
Jim Smith, £1000

*/
19 January 2012