IComparable vs IComparer interfaces in Visual C#


The role of IComparable is to provide a method of comparing two objects of a particular type. This is necessary if you want to provide any ordering capability for your object. Think of IComparable as providing a default sort order for your objects. For example, if you have an array of objects of your type, and you call the Sort method on that array, IComparable provides the comparison of objects during the sort. When you implement the IComparable interface, you must implement the CompareTo method.

The role of IComparer is to provide additional comparison mechanisms. For example, you may want to provide ordering of your class on several fields or properties, ascending and descending order on the same field, or both.

Using IComparer is a two-step process. First, declare a class that implements IComparer, and then implement the Compare method.

    public class Car : IComparable
public int ID { get; set; }
public string PetName { get; set; }

public Car(string petName, int id)
PetName = petName;
ID = id;

// IComparable implementation.
int IComparable.CompareTo(object obj)
Car temp = (Car)obj;
return this.ID.CompareTo(temp.ID);

public class PetNameComparer : IComparer
// Test the pet name of each object.
int IComparer.Compare(object o1, object o2)
Car t1 = (Car)o1;
Car t2 = (Car)o2;
return String.Compare(t1.PetName, t2.PetName);

// Car[] cars = {...}; // Array of cars

// Following example uses IComparable interface
// Array.Sort(cars);

// Following example uses IComparer Interface
// Array.Sort(cars, new PetNameComparer());

posted under , , |
Newer Post Older Post Home
This is my personal blog to share my research on Web related Technologies as well as Inner Well Being.