Understanding Generics—Creating Generic Structures (or Classes)

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
CSharp-Online.NET:Articles
C# Articles

Understanding Generics

© 2006 Andrew Troelsen

Creating Generic Structures (or Classes)

Now that you understand how to define and invoke generic methods, let’s turn our attention to the construction of a generic structure (the process of building a generic class is identical). Assume you have built a flexible Point structure that supports a single type parameter representing the underlying storage for the (x, y) coordinates. The caller would then be able to create Point<T> types as so:

// Point using ints.
Point<int> p = new Point<int>(10, 10);
 
// Point using double.
Point<double> p2 = new Point<double>(5.4, 3.3);

Here is the complete definition of Point<T>, with analysis to follow:

// A generic Point structure.
public struct Point<T>
{
   // 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()
   {
      xPos = default(T);
      yPos = default(T);
   }
}


Previous_Page_.gif Next_Page_.gif

Personal tools