July 2005
Intermediate to advanced
644 pages
17h
English
Because of the native support for generics in the IL and the CLR, all CLR 2.0-compliant languages can take advantage of generic types. For example, here is some Visual Basic 2005 code that uses the generic stack of Example D-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<T>
{
public T X;
public T Y;
}You can use the generic Point for integer coordinates:
Point<int> point;
point.X = 1;
point.Y = 2;or for charting coordinates that require floating-point precision:
Point<double> point;
point.X = 1.2;
point.Y = 3.4;A single type can define multiple generic type parameters. For example, consider the generic linked list shown in Example D-3.
Example D-3. A generic linked list
class Node<K,T>
{
public K Key;
public T Item;
public Node<K,T> NextNode;
public Node()
{
Key = default(K);
Item = default(T);
NextNode = null;
}
public Node(K key,T item,Node<K,T> nextNode)
{
Key = key;
Item = item;
NextNode = nextNode;
}
}
public class LinkedList<K,T>
{
Node<K,T> m_Head;
public LinkedList()
{
m_Head = new Node<K,T>();
}
public void AddHead(K key,T item)
{
Node<K,T> newNode = new Node<K,T>(key,item,m_Head.NextNode);
m_Head.NextNode = newNode;
}
}The linked list stores nodes:
class Node<K,T>
{...}Each node contains a key (of the generic type parameter K) and a value (of the generic ...