.NET Tip “IComparable.CompareTo()” Vs “IComparer.Compare()”

class Employee {   public int  EmployeeID { get; set; }   public string FirstName { get; set; }   public  string LastName { get; set; }   public int yearofExperience { get; set;  }   public int DesignationRank { get; set; }

  public Employee(int empID, string  fName, string lName, int yof, int    desRank)   {     EmployeeID =  empID;     FirstName = fName;     LastName = lName;      yearofExperience = yof;     DesignationRank = desRank;    }

Suppose we created an employee collection as  follow.

List liEmployee  = new List(); liEmployee.Add(new  Employee(612, “Madhusmita”, “Rout”, 3, 3)); liEmployee.Add(new Employee(314,  “soumyashree”, “Mishra”, 5, 1)); liEmployee.Add(new Employee(16, “Anand”,  “Keshari”, 12, 2));

Let’s say now we want to sort Employee collection by  calling the default sort method, what will happen?

When we call the liEmployee.Sort() method, suprisingly  it will generate the exception “Failed to compare the elements in the  array” with inner exception “at least one  object must  implement Icomparable”.

The reason of exception is clear hear, as there is  not clearly mentioned on what basis the employee collection should be sorted i.e. on name, year of experience, on the basis of  employee id or on designation rank. So .Net framework fails to sort the employee  collection.

So to allow the collection of employee objects to be  sorted by default we need to implement ICopmareble interface and its CompareTo()  method.So we need to enhance the Employee class as mentioned  below.

//Implement the  IComparable interface

class  Employee:IComparable {     public int EmployeeID { get;  set; }     public string FirstName { get; set; }     public string  LastName { get; set; }     public int yearofExperience { get; set; }      public int DesignationRank { get; set; }

  public Employee(int empID, string  fName, string lName, int yof, int       desRank)   {     EmployeeID =  empID;     FirstName = fName;     LastName = lName;      yearofExperience = yof;     DesignationRank = desRank; }

//Implement the CompateTo  method public int CompareTo(Employee other) {    if (this.EmployeeID  > other.EmployeeID)     {        return 1;     }    else if  (this.EmployeeID < other.EmployeeID)    {      return -1;    }     else    {      return 0;    } }

}

So now after implementing  the IComparable interface and its CompareTo() method list will be sorted the  employee collection without fail.

Now when we call liEmployee.Sort() it will sort the Employee collection on  the basis of employee id.

foreach (Employee emp in liEmployee) {      Debug.WriteLine(emp.FirstName + “” + emp.LastName); }

150 150 Burnignorance | Where Minds Meet And Sparks Fly!