Introduction:
We all know about ArrayList and its functionlity, it is the dynamic array of the .Net Framework, where you can add, delete, search & sort objects in it. The issue we will descuss in this article is Sorting ArrayList.
Define the issue:
The problem is stated in MSDN in the definition of the Sort method it says: "Sorts the elements in the entire ArrayList using the IComparable implementation of each element". which means that any object in the ArrayList that you wish to sort must implement the IComparable interface. I think most of .Net Framework implements the IComparable interface like Int32,Int16...,String,Decimal etc.... but what about our own types??!! the Classes and structures we build ourselvs?? do we still able to sort them??!!! yes we can do that, but note that those will be complex type, which mean that you have to know what is the parameter you are going to use to sort your own defined types, and this what we are going to see in the next sections.
Note: :if you tried to sort and array or an ArrayList that is containing your defined type, and this type do not implement the IComparable interface, you will get an exception.
IComparable interface:
By looking in the MSDN, I found the IComparable interface has only one method, CompareTo which take only one parameter of type object, which mean it can accept any type, and returns an integer which mean the following:
- Less than zero if this instance is less than obj.
- Zero if this instance is equal to obj.
- Greater than zero if this instance is greater than obj.
So all we have to do when building our own type is to implement the IComparable interface example:
public class Employee : System.IComparable
{
//....code
public int CompareTo(object obj)
{
//..implementation
}
}