Free mag vol1 | Page 379

CHAPTER 8  WORKING WITH INTERFACES static void Main(string[] args) { ... // Now sort by pet name. Array.Sort(myAutos, new PetNameComparer()); // Dump sorted array. Console.WriteLine("Ordering by pet name:"); foreach(Car c in myAutos) Console.WriteLine("{0} {1}", c.CarID, c.PetName); ... } Custom Properties and Custom Sort Types It is worth pointing out that you can make use of a custom static property in order to help the object user along when sorting your Car types by a specific data point. Assume the Car class has added a static readonly property named SortByPetName that returns an instance of an object implementing the IComparer interface (PetNameComparer, in this case): // We now support a custom property to return // the correct IComparer interface. public class Car : IComparable { ... // Property to return the PetNameComparer. public static IComparer SortByPetName { get { return (IComparer)new PetNameComparer(); } } } The object user code can now sort by pet name using a strongly associated property, rather than just “having to know” to use the stand-alone PetNameComparer class type: // Sorting by pet name made a bit cleaner. Array.Sort(myAutos, Car.SortByPetName);  Source Code The ComparableCar project is located under the Chapter 8 subdirectory. Hopefully, at this point you not only understand how to define and implement your own interfaces, but also understand their usefulness. To be sure, interfaces are found within every major .NET namespace, and you will continue working with various standard interfaces over the remainder of this text. 317