Free mag vol1 | Page 398

CHAPTER 9  COLLECTIONS AND GENERICS Specifying Type Parameters for Generic Interfaces It is common to implement generic interfaces when you build classes or structures that need to support various framework behaviors (e.g., cloning, sorting, and enumeration). In Chapter 8, you learned about a number of nongeneric interfaces, such as IComparable, IEnumerable, IEnumerator, and IComparer. Recall that the nongeneric IComparable interface was defined like this: public interface IComparable { int CompareTo(object obj); } In Chapter 8, you also implemented this interface on your Car class to enable sorting in a standard array. However, the code required several runtime checks and casting operations because the parameter was a general System.Object: public class Car : IComparable { ... // IComparable implementation. int IComparable.CompareTo(object obj) { Car temp = obj as Car; if (temp != null) { if (this.CarID > temp.CarID) return 1; if (this.CarID < temp.CarID) return -1; else return 0; } else throw new ArgumentException("Parameter is not a Car!"); } } Now assume you use the generic counterpart of this interface: public interface IComparable { int CompareTo(T obj); } In this case, your implementation code will be cleaned up considerably: public class Car : IComparable { ... // IComparable implementation. int IComparable.Compa reTo(Car obj) { if (this.CarID > obj.CarID) return 1; 337