Free mag vol1 | Page 375

CHAPTER 8  WORKING WITH INTERFACES The IComparable Interface The System.IComparable interface specifies a behavior that allows an object to be sorted based on some specified key. Here is the formal definition: // This interface allows an object to specify its // relationship between other like objects. public interface IComparable { int CompareTo(object o); }  Note The generic version of this interface (IComparable) provides a more type-safe manner to handle comparisons between objects. You’ll examine generics in Chapter 9. Let’s assume you have a new Console Application named ComparableCar that defines the following updated Car class (notice that we have basically just added a new property to represent a unique ID for each car and a modified constructor): public class Car { ... public int CarID {get; set;} public Car(string name, int currSp, int id) { CurrentSpeed = currSp; PetName = name; CarID = id; } ... } Now assume you have an array of Car objects as follows: static void Main(string[] args) { Console.WriteLine("***** Fun with Object Sorting *****\n"); // Make an array of Car objects. Car[] myAutos = new Car[5]; myAutos[0] = new Car("Rusty", 80, 1); myAutos[1] = new Car("Mary", 40, 234); myAutos[2] = new Car("Viper", 40, 34); myAutos[3] = new Car("Mel", 40, 4); myAutos[4] = new Car("Chucky", 40, 5); Console.ReadLine(); } 313