Free mag vol1 | Page 415

CHAPTER 9  COLLECTIONS AND GENERICS xPos = default(T); yPos = default(T); } } The default Keyword in Generic Code As you can see, Point leverages its type parameter in the definition of the field data, constructor arguments, and property definitions. Notice that, in addition to overriding ToString(), Point defines a method named ResetPoint() that uses some new syntax you have not yet seen: // The "default" keyword is overloaded in C#. // When used with generics, it represents the default // value of a type parameter. public void ResetPoint() { X = default(T); Y = default(T); } With the introduction of generics, the C# default keyword has been given a dual identity. In addition to its use within a switch construct, it can also be used to set a type parameter to its default value. This is helpful because a generic type does not know the actual placeholders up front, which means it cannot safely assume what the default value will be. The defaults for a type parameter are as follows: • Numeric values have a default value of 0. • Reference types have a default value of null. • Fields of a structure are set to 0 (for value types) or null (for reference types). For Point, you can set the X and Y values to 0 directly because it is safe to assume the caller will supply only numerical data. However, you can also increase the overall flexibility of the generic type by using the default(T) syntax. In any case, you can now exercise the methods of Point: static void Main(string[] args) { Console.WriteLine("***** Fun with Generic Structures *****\n"); // Point using ints. Point p = new Point(10, 10); Console.WriteLine("p.ToString()={0}", p.ToString()); p.ResetPoint(); Console.WriteLine("p.ToString()={0}", p.ToString()); Console.WriteLine(); // Point using double. Point p2 = new Point(5.4, 3.3); Console.WriteLine("p2.ToString()={0}", p2.ToString()); p2.ResetPoint(); Console.WriteLine("p2.ToString()={0}", p2.ToString()); 354