IComparable Defined:
This interface defines a comparison method that most of the value types like int, double, string implement to sort the instances. This inherited type implements the CompareTo() method returning an int to indicate whether current instance in sort order is before, after or same as the second object.
Examples:
Array and ArraList implement this interface and have a Sort() method that sorts the objects in the list. Have a look at this simple example:
int[] iArray = new int[4];
iArray[0] = 3;
iArray[1] = 4;
iArray[2] = 1;
iArray[3] = 2;Array.Sort(iArray);
foreach (int i in iArray)
{
Console.WriteLine(i);
}
This will print the integers sorted no matter in which order they were entered:
1
2
3
4
Doing this however will result in System.ArgumentException as inner exception of System.InvalidOperationException:
Employee[] eArray = new Employee[4];
eArray[0] = new Employee(“Ali”, 40, 3000);
eArray[1] = new Employee(“Dawood”, 50, 3000);
eArray[2] = new Employee(“Ehsan”, 20, 3000);
eArray[3] = new Employee(“Zulfiqar”, 30, 3000);Array.Sort(eArray);
Implementation:
Its really easy I must say, how ? see this example:
public class Employee: IComparable
{
public string Name { get; set; }
public int Age { get; set; }
public double Salary { get; set; }public Employee(string name, int age, double salary)
{
this.Name = name;
this.Age = age;
this.Salary = salary;
}#region IComparable Members
public int CompareTo(object obj)
{
// lets implement for Age
Employee tempEmp = obj as Employee;
if (tempEmp != null)
{
//======== Use one ==============
// 1. a lengthy way
if (this.Age > tempEmp.Age) { return 1; } // comes after the instance
if (this.Age < tempEmp.Age) { return -1; } // comes before instance
else { return 0; } // both equal// 2. or could use easier one as Age already implements CompareTo()
return this.Age.CompareTo(tempEmp.Age);
}
else
{
throw new ArgumentException(“Object is not an Employee”);
}
}#endregion
}
Now sort the Employee array ans see the difference.



