Free mag vol1 | Page 414

CHAPTER 9  COLLECTIONS AND GENERICS Creating Custom Generic Structures and Classes Now that you understand how to define and invoke generic methods, it’s time to turn your attention to the construction of a generic structure (the process of building a generic class is identical) within a new Console Application project named GenericPoint. Assume you have built a generic Point structure that supports a single type parameter that represents the underlying storage for the (x, y) coordinates. The caller can then create Point types as follows: // Point using ints. Point p = new Point(10, 10); // Point using double. Point p2 = new Point(5.4, 3.3); Here is the complete definition of Point, with some analysis to follow: // A generic Point structure. public struct Point { // Generic state date. private T xPos; private T yPos; // Generic constructor. public Point(T xVal, T yVal) { xPos = xVal; yPos = yVal; } // Generic properties. public T X { get { return xPos; } set { xPos = value; } } public T Y { get { return yPos; } set { yPos = value; } } public override string ToString() { return string.Format("[{0}, {1}]", xPos, yPos); } // Reset fields to the default value of the // type parameter. public void ResetPoint() { 353