Understanding Generics—The default Keyword in Generic Code
The default Keyword in Generic Code
As you can see, Point<T> leverages its type parameter in the definition of the field data, constructor
arguments, and property definitions. Notice that in addition to overriding ToString(), Point<T>
defines a method named ResetPoint() that makes use of some new syntax:
// The 'default' keyword is overloaded in C# 2005. // when used with generics, it represents the default // value of a type parameter. public void ResetPoint() { xPos = default(T); yPos = default(T); }
Under C# 2005, the default keyword has been given a dual identity. In addition to its use
within a switch construct, it can be used to set a type parameter to its default value. This is clearly
helpful given that a generic type does not know the actual placeholders up front and therefore 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<T>, you could simply set xPos and yPos to 0 directly, given that it is safe to assume the
caller will supply only numerical data. However, by using the default(T) syntax, you increase the overall
flexibility of the generic type. In any case, you can now exercise the methods of Point<T> as so:
static void Main(string[] args) { Console.WriteLine("***** Fun with Generics *****\n"); // Point using ints. Point<int> p = new Point<int>(10, 10); Console.WriteLine("p.ToString()={0}", p.ToString()); p.ResetPoint(); Console.WriteLine("p.ToString()={0}", p.ToString()); Console.WriteLine(); // Point using double. Point<double> p2 = new Point<double>(5.4, 3.3); Console.WriteLine("p2.ToString()={0}", p2.ToString()); p2.ResetPoint(); Console.WriteLine("p2.ToString()={0}", p2.ToString()); Console.WriteLine(); // Swap 2 Points. Point<int> pointA = new Point<int>(50, 40); Point<int> pointB = new Point<int>(543, 1); Console.WriteLine("Before swap: {0}, {1}", pointA, pointB); Swap<Point<int>>(ref pointA, ref pointB); Console.WriteLine("After swap: {0}, {1}", pointA, pointB); Console.ReadLine(); }
Figure 10-2 shows the output.
![]()
Figure 10-2. Using the generic Point type
|

