CHAPTER 8 WORKING WITH INTERFACES
We can streamline the previous implementation of CompareTo() given the fact that the C# int data
type (which is just a shorthand notation for the CLR System.Int32) implements IComparable. You could
implement the Car’s CompareTo() as follows:
int IComparable.CompareTo(object obj)
{
Car temp = obj as Car;
if (temp != null)
return this.CarID.CompareTo(temp.CarID);
else
throw new ArgumentException("Parameter is not a Car!");
}
In either case, so that your Car type understands how to compare itself to like objects, you can write
the following user code:
// Exercise the IComparable interface.
static void Main(string[] args)
{
// Make an array of Car objects.
...
// Display current array.
Console.WriteLine("Here is the unordered set of cars:");
foreach(Car c in myAutos)
Console.WriteLine("{0} {1}", c.CarID, c.PetName);
// Now, sort them using IComparable!
Array.Sort(myAutos);
Console.WriteLine();
}
// Display sorted array.
Console.WriteLine("Here is the ordered set of cars:");
foreach(Car c in myAutos)
Console.WriteLine("{0} {1}", c.CarID, c.PetName);
Console.ReadLine();
Here is the output from the previous Main() method:
***** Fun with Object Sorting *****
Here is the unordered set of cars:
1 Rusty
234 Mary
34 Viper
4 Mel
5 Chucky
Here is the ordered set of cars:
1 Rusty
4 Mel
5 Chucky
315