Applying Generics
Because of the native support for generics in the IL and the CLR, most CLR-compliant language can take advantage of generic types. For example, here is some Visual Basic .NET code that uses the generic stack of Code block 2:
Dim stack As Stack(Of Integer)
stack = new Stack(Of Integer)
stack.Push(3)
Dim number As Integer
number = stack.Pop()
You can use generics in classes and in structs. Here is a useful generic point struct:
public struct Point
{
public T X;
public T Y;
}
You can use the generic point for integer coordinates, for example:
Point
point.X = 1;
point.Y = 2;
Or for charting coordinates that require floating point precision:
Point
point.X = 1.2;
point.Y = 3.4;
Besides the basic generics syntax presented so far, C# 2.0 has some generics-specific syntax. For example, consider the Pop() method of Code block 2. Suppose instead of throwing an exception when the stack is empty, you would like to return the default value of the type stored in the stack. If you were using an Object-based stack, you would simply return null, but a generic stack could be used with value types as well. To address this issue, you can use the default() operator, which returns the default value of a type.
Here is how you can use default in the implementation of the Pop() method:
public T Pop()
{
m_StackPointer--;
if(m_StackPointer >= 0)
{
return m_Items[m_StackPointer];
}
else
{
m_StackPointer = 0;
return default(T);
}
}