Let us take an example of Student objects, with properties Id (int), Name (String), Height (double) etc. If we need to sort a collection (say an Array or Arraylist) of student objects on their Ids, or Names or Heights all we need to do is, to implement the IComparable interface and use the CompareTo() method of the respective data type in the implementation for the CompareTo() method in the Student Class.
For example if i need to sort on the Id (an int), the following would be the implementation of the compareTo() function.
But what if i add a new property called EyeColor, which is of Type System.Drawing.Color that does not have its own CompareTo() Implementation?
We need to supply an implementation that tells the Array or the ArrayList how the two instances are decided as > or = or < when compared to each other.
I could sort out this problem by using the GetHashcode() of Color instance, which returns an integer which inturn has its own CompareTo() method to be readily used.
I wrote a sample application using this logic to sort colored balls in a pipe, in groups of the simillar color.
There are 2 classes one for pipe and the other for the Ball. In the ball implements the IComparable interface and its CompareTo() is as follows...