Using IComparable and IComparer to compare objects

Introduction

The .Net framework and especially the System.Collection namespace provides us two built in interfaces which are IComparable and IComparer interfaces. The first one, namely, the IComparable specifies a behavior that allows an object to be compared to another one from the same type according to a specified member value such as a hash table value or so. At the other hand, IComparer interface enables us to compare two objects at once at the opposite of the first one which enables us to compare two objects one by one. The IComparable and the IComparer could also be found as a part of the System.Collection. Generic built-in interfaces, thing that renders the deal more comfortable when using them since the conversion exceptions headache will be neutralized and avoided with generic types.

In this article, I will try to provide some techniques according to the effective use of the IComparable and the IComparer interfaces in a development context and I will expose some real use cases to know how, and under which condition may one use each of both interfaces.

IComparable interface

interface
{
    int CompareTo (object o);
}

The IComparable interface has CompareTo (object o) as a member. This last one is used to compare two objects one by one profiting of the extreme polymorphism nature of the interface. Say, that we have a type person and you want to compare two objects from this type according to their ages for example. It will be more practical to implement the IComparable interface within the person class core.

public class Person : IComparable
{
    public Person() { }
    // private fields
    private string _FirstName;
    private string _LastName;
    private int _Age;
    public Person(string FirstName, string LastName, int Age)
    {
        this.FirstName = FirstName;
        this.LastName = LastName;
        this.Age = Age;
    }
    //Properties
    public string FirstName
    {
        get { return _FirstName; }
        set { _FirstName = value; }
    }
    public string LastName
    {
        get { return _LastName; }
        set { _LastName = value; }
    }
    public int Age
    {
        get { return _Age; }
        set { _Age = value; }
    }
    //This was the interface member
    public int CompareTo(object obj)
    {
        Person Temp = (Person)obj;
        if (this.Age < Temp.Age)
        { return 1; }
        if (this.Age > Temp.Age)
        { return -1; }
        else
        { return 0; }
    }
}

The method int CompareTo (object obj) returns an integer. You can specify your result according to the returned value as follow:

class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Hello World!"); 
        // TODO: Implement Functionality Here
        Person me = new Person("Bejaoui", "Bechir", 29);
        Person myFather = new Person("Bejaoui", "Massinissa", 65);
        Person myGrandFather = new Person("Krayem", "Shishaq", 95);
        int state = me.CompareTo(myFather);
        if (state == 1) Console.WriteLine("My father is older than me");
        if (state == -1) Console.WriteLine("I'm older than my father!!!");
        if (state == 0) Console.WriteLine("My Father and I have the same age!");
        Console.Write("Press any key to continue . . . ");
        Console.ReadKey(true);
    }
}

When the generics come into the world as a part of the .Net 2.0 innovations, the code structure becomes more robust as the problem that may raise a casting exception is avoided in this case. So the person class code structure will be as following:

public class Person : IComparable<Person>
{
    public Person() { }
    // private fields
    private string _FirstName;
    private string _LastName;
    private int _Age;
    public Person(string FirstName, string LastName, int Age)
    {
        this.FirstName = FirstName;
        this.LastName = LastName;
        this.Age = Age;
    }
    //Properties
    public string FirstName
    {
        get { return _FirstName; }
        set { _FirstName = value; }
    }
    public string LastName
    {
        get { return _LastName; }
        set { _LastName = value; }
    }
    public int Age
    {
        get { return _Age; }
        set { _Age = value; }
    }
    //This was the interface member
    public int CompareTo(Person obj)
    {
        Person Temp = obj;
        if (this.Age < Temp.Age)
        { return 1; }
        if (this.Age > Temp.Age)
        return -1; }
        else
        { return 0; }
    }
}

You can observe that the argument that overloads the CompareTo is a type of person rather than object now. With this manner the casting operation is avoided and the risk of receiving a compile or a run time errors are minimized. But let us be more practical as this example is demystifying the fact of profiting of the real IComparable interface services. I explain by giving a real example. The array type implements the IComparable interface in order to sort its objects collection and even the array list do the same thing to sort its objects collection internally.

Say that I want to build my own objects container type. For this, I build a new type called Room which plays the role of person objects container.

The class person will be presented as follow:

public class Person
{
    public Person() { }
    // private fields
    private string _FirstName;
    private string _LastName;
    private int _Age;
    public Person(string FirstName, string LastName, int Age)
    {
        this.FirstName = FirstName;
        this.LastName = LastName;
        this.Age = Age;
    }
    //Properties
    public string FirstName
    {
        get { return _FirstName; }
        set { _FirstName = value; }
    }
    public string LastName
    {
        get { return _LastName; }
        set { _LastName = value; }
    }
    public int Age
    {
        get { return _Age; }
        set { _Age = value; }
    }
}

The class Room witch plays the container role is designed as bellow:

public class Room
{
    protected ArrayList oList;
    public Room()
    {
        oList = new ArrayList();
    }
    //Indexer
    public Person this[int index]
    {
        get { return (Person)oList[index]; }
        set { oList[index] = value; }
    }
    //Properties
    public int Count
    {
        get { return oList.Count; }
    }
    //Methods
    public void AddNewPerson(Person o)
    {
        oList.Add(o);
    }
    public void SortByAge()
    {
        oList.Sort();
    }
    public void ReverseByAge()
    {
        oList.Reverse();
    }
}

When I try to run this program:

class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");
        // TODO: Implement Functionality Here
        Person me = new Person("Bejaoui","Bechir",29);
        Person myFather = new Person("Bejaoui","Massinissa",65);
        Person myGrandFather = new Person("Bejaoui","Shishaq",95);
        //Add some persons to the room
        Room LivingRoom = new Room();
        LivingRoom.AddNewPerson(me);
        LivingRoom.AddNewPerson(myFather);
        LivingRoom.AddNewPerson(myGrandFather);
        LivingRoom.SortByAge();
        for(int i = 0; i<LivingRoom.Count;i++)
        {
            Console.WriteLine( "First name : " + LivingRoom[i].FirstName + Environment.NewLine );
            Console.WriteLine( "Last name : " + LivingRoom[i].LastName + Environment.NewLine );
            Console.WriteLine( "Age : " + LivingRoom[i].Age + Environment.NewLine );
        }
        Console.WriteLine("*** After reversing according to age ***" + Environment.NewLine);
        LivingRoom.ReverseByAge();
        for(int i = 0; i<LivingRoom.Count;i++)
        {
            Console.WriteLine( "First name : " + LivingRoom[i].FirstName + Environment.NewLine );
            Console.WriteLine( "Last name : " + LivingRoom[i].LastName + Environment.NewLine );
            Console.WriteLine( "Age : " + LivingRoom[i].Age + Environment.NewLine );
        }
        Console.WriteLine("Done");
        Console.Write("Press any key to continue . . . ");
        Console.ReadKey(true); Console.Beep();
    }
}

I receive a real time error that indicates that the sorting operation is failed and the cause here is that the person type doesn't implement the IComparable interface. In order to render the sorting operation realizable, the IComparable interface has to be implemented first. Try now to implement the person type as follow:

public class Person : IComparable
{
    public Person() { }
    // private fields
    private string _FirstName;
    private string _LastName;
    private int _Age;
    public Person(string FirstName, string LastName, int Age)
    {
        this.FirstName = FirstName;
        this.LastName = LastName;
        this.Age = Age;
    }
    //Properties
    public string FirstName
    {
        get { return _FirstName; }
        set { _FirstName = value; }
    }
    public string LastName
    {
        get { return _LastName; }
        set { _LastName = value; }
    }
    public int Age
    {
        get { return _Age; }
        set { _Age = value; }
    }
    //Interface method
    public int CompareTo(object o)
    {
        Person Temp = (Person)o;
        if (this.Age < Temp.Age)
        {
            return 1;
        }
        if (this.Age > Temp.Age)
        {
            return -1;
        }
        else
        {
            return 0;
        }
    }
}

Now, try to run the program and you will not receive this run time error again. Well, the fact is that this interface method enables the object to be compared to other instances of its own type.

IComparer interface

At the other hand, the IComparer interface is used to compare two objects issued from the same type and at the same time, consequently, it doesn't be implemented within the type going to be compared. It is implemented within a separate type that has as a mission to compare a couple of objects. Let us turn back to our previous example and try to use the IComparer instead of the IComparable interface to sort objects within the room container.

Given this design of person type:

public class Person
{
    public Person() { }
    // private fields
    private string _FirstName;
    private string _LastName;
    private int _Age;
    public Person(string FirstName, string LastName, int Age)
    {
        this.FirstName = FirstName;
        this.LastName = LastName;
        this.Age = Age;
    }
    //Properties
    public string FirstName
    {
        get { return _FirstName; }
        set { _FirstName = value; }
    }
    public string LastName
    {
        get { return _LastName; }
        set { _LastName = value; }
    }
    public int Age
    {
        get { return _Age; }
        set { _Age = value; }
    }
}

Say that we want to sort objects person by name now. First we ought to define a kind for comparer object that implements the IComparer interface:

/// <summary>
/// CompareByName is an object that enables us compare
/// two person objects, it implements the IComprer interface.
/// </summary>
public class CompareByName : IComparer
{
    public CompareByName() { }
    //Implementing the Compare method
    public int Compare(object object1, object object2)
    {
        Person Temp1 = (Person)object1;
        Person Temp2 = (Person)object2;
        return string.Compare(Temp1.FirstName, Temp2.FirstName);
    }
}

Then we implement the Room container as follow:

public class Room
{
    protected ArrayList oList;
    public Room()
    {
        oList = new ArrayList();
    }
    //Indexer
    public Person this[int index]
    {
        get
        {
            return (Person)oList[index];
        }
        set
        {
            oList[index] = value;
        }
    }
    //Properties
    public int Count
    {
        get
        {
            return oList.Count;
        }
    }
    //Methods
    public void AddNewPerson(Person o)
    {
        oList.Add(o);
    }
    public void SortByAge()
    {
        CompareByName Comparer = new CompareByName();
        oList.Sort(Comparer);
    }
    public void ReverseByAge()
    {
        oList.Reverse();
    }
}

As you observe, I instantiate a CompareByName object which serves as an argument to overload the oList.Sort method and that enables the Room container to compare the person objects collection twice by twice internally.


Similar Articles