Skip to Main Content
Programming .NET Components, 2nd Edition
book

Programming .NET Components, 2nd Edition

by Juval Lowy
July 2005
Intermediate to advanced content levelIntermediate to advanced
644 pages
17h
English
O'Reilly Media, Inc.
Content preview from Programming .NET Components, 2nd Edition

Applying Generics

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;

Multiple Generic Types

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Windows Forms Programming in C#

Windows Forms Programming in C#

Chris Sells
Metaprogramming in .NET

Metaprogramming in .NET

Jason Bock, Kevin Hazzard
.NET Windows Forms in a Nutshell

.NET Windows Forms in a Nutshell

Ian Griffiths, Matthew Adams

Publisher Resources

ISBN: 0596102070Supplemental ContentErrata Page