C#
  Home arrow C# arrow Page 2 - Building C# Comparable Objects: IComparabl...
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Mobile Linux 
App Generation ROI 
Windows Web Hosting
 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C#

Building C# Comparable Objects: IComparable versus IComparer
By: Ayad Boudiab
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 3
    2008-08-04

    Table of Contents:
  • Building C# Comparable Objects: IComparable versus IComparer
  • Sorting Objects
  • Quick Recap
  • Full Program

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Building C# Comparable Objects: IComparable versus IComparer - Sorting Objects


    (Page 2 of 4 )

    In our first attempt to sort objects, we create an Employee class with name and id. In the Main() method we create an array of five employees. The System.Array class provides a Sort() method that sorts an array of objects. When we try to run the following code we end up with a runtime exception: “At least one object must implement IComparable.” In other words, the error is asking us what we mean by sorting employees.

    class Program

    {

    static   void Main( string [] args)

    {

    Employee[] employees = new Employee[5];

    employees[0] = new Employee( "Dan K." , 12456);

    employees[1] = new Employee( "Jim L." , 99584);

    employees[2] = new Employee( "Tony T." , 51472);

    employees[3] = new Employee( "Jessica W." , 32788);

    employees[4] = new Employee( "Leda B." , 44110);


    //**Runtime exception: at least one object must

    //**implement IComparable

    Array .Sort(employees);

    }

    }


    class Employee

    {

    private   string name;

    public   string Name

    {

    get { return name; }

    set { name = value ; }

    }

    private   int id;

    public   int Id

    {

    get { return id; }

    set { id = value ; }

    }


    public Employee( string a_name, int an_id)

    {

    name = a_name;

    id = an_id;

    }

    }

    It is clear then that we need to implement the IComparable interface to be able to sort the array of employees. The IComparable interface contains a single method called CompareTo:

      public   int CompareTo( object obj)

    The method accepts an object as a parameter and returns an integer. Since object is the parent of all objects, passing an Employee or any other object will work. The return value could be positive, negative, or zero:

    • A return value of zero means that the two objects we are comparing are equal to each other.

    • A negative return value means that the first object comes before the second object.

    • A positive return value means that the first object comes after the second object.

    The first thing we do in the CompareTo method is cast the object parameter into an Employee object. The we compare this object with the newly casted Employee object. In this case we decided to compare them by id. Here is how the code will look:

    class Program

    {

    static   void Main( string [] args)

    {

    Employee[] employees = new Employee[5];

    employees[0] = new Employee( "Dan K." , 12456);

    employees[1] = new Employee( "Jim L." , 99584);

    employees[2] = new Employee( "Tony T." , 51472);

    employees[3] = new Employee( "Lee W." , 32788);

    employees[4] = new Employee( "Leda B." , 44110);


    Array .Sort(employees);

    foreach (Employee e in employees)

    Console .WriteLine(e);

    }

    }


    class Employee : IComparable

    {

    private   string name;

    public   string Name

    {

    get { return name; }

    set { name = value ; }

    }

    private   int id;

    public   int Id

    {

    get { return id; }

    set { id = value ; }

    }


    public Employee( string a_name, int an_id)

    {

    name = a_name;

    id = an_id;

    }


    public   override   string ToString()

    {

    return   string .Format( "Name: {0}ttId: {1}" ,

    Name, Id);

    }


    #region IComparable Members


    public   int CompareTo( object obj)

    {

    Employee temp = (Employee)obj;

    if ( this .Id > temp.Id)

    return 1;

    if ( this .Id < temp.Id)

    return -1;

    else

    return 0;

    }


    #endregion

    }

    In the Main() method, we sort the employees array in place and we use the foreach loop to print the list of employees. Try to run the code and notice in the output how the objects are sorted by id.

    More C# Articles
    More By Ayad Boudiab


       · Welcome to my latest C# article. I am looking forward to your feedback.
       · Excellent work. New things are introduced at the right time in this article, that...
       · Excellent work. New things are introduced at the right time in this article, that...
     

    C# ARTICLES

    - Working with Dates and Times in C#
    - Generics, Dictionaries, and More
    - More About Generics
    - Working with C# Collections
    - Generics
    - C# and XML
    - Pointers and Arrays in C#
    - C# 3.0 Extension Methods
    - Overloading Operators in C#
    - Iterators and Nullable Types
    - Patterns and Iterators in C#
    - C# Exceptions
    - Methods in C#
    - Delegates and Events in C#
    - Advanced C#

     
    Best Practices for Windows Vista Migration Presentation
    Dell and Microsoft recently held a series of face-to-face seminars entitled, &qu....

     
    Creating a Culture for Code Reuse
    If you oversee development teams you know that like it or not proprietary and ex....

     
    Keys to Web Application Acceleration: Advances in Delivery Systems
    Accelerate Web apps by up to 5x. Ensure significantly faster access to the Web a....

     
    Optimizing Application Monitoring
    Tired of finding out from your customers that you're offline? This white paper e....

     
    Solaris to Solaris Migration -- Migrating applications from Sun SPARC to Dell PowerEdge R900
    This comprehensive Migration Guide reviews the approach that Principled Technolo....

     




    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 3 hosted by Hostway
    Stay green...Green IT