Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
World Class ASP.NET Hosting - 3 Month Free Hosting, Click Here!
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » ASP.NET & Web Forms » Using IComparable and IComparer to compare objects

Using IComparable and IComparer to compare objects

This article informs you that the .Net framework and especially the System.Collection namespace provides us two built in interfaces witch are IComparable and IComparer interfaces that enables us compare and sort objects.

Author Rank:
Technologies: .NET 1.0/1.1,Visual C# .NET
Total downloads :
Total page views :  7368
Rating :
 3/5
This article has been rated :  2 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
Powerful ASP.NET Hosting w/ NO Setup Fees. Click Here!
Become a Sponsor


Related EbooksTop Videos

Introduction

The .Net framework and especially the System.Collection namespace provides us two built in interfaces witch 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 witch 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 witch 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 witch 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 an CompareByName object witch 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.


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Bechir Bejaoui
The author holds a master degree in NTIC specialized  in software developement delivered by the high school of communication SUPCOM, he also holds a bachelor degree in finance delivered by  the  economic sciences and  management  university of Tunis "FSEGT". He's a freelance developer since 2006. Actually woking on the WPF, .Net framewok 3.5, silverlight and the other .Net new features, in addition, he is painter and sculptor.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Microsoft Visual Studio 2010 offers more to developers than any other Visual Studio release. Work more productively and collaboratively-with greater control over your work at every step. The Beta 2 can give you a head start on achieving efficiency.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved