New Features in C# 2.0—Generic Collection: What just happened?

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


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

New Features in C# 2.0

© 2005 O'Reilly Media, Inc.

What just happened?

You just created a generic linked list; one that is type-safe for any type of object you hold in the collection. In fact, one way to create a linked list such as this is to start by creating a type-specific linked list. This simple example works by defining a generic linked list whose head node is initialized to null:

public class LinkedList<T>
{
  private Node<T> headNode = null;
  ...
}

When you add data to the linked list, a new node is created and if there is no head node, that new node becomes the head; otherwise, append is called on the head node.

Each node checks to see if its next field is null (and thus the current node is the end of the list). If so, the current node appends the new node; otherwise, it passes the new node to the next member in the list.

Notice that LinkedList is intentionally declared with the same generic type parameter as Node. Because they both use the same letter (T), the compiler knows that the type used to substitute for T in LinkedList will be the same type used to substitute for T<code> in <code>Node. This makes sense: a linked list of integers will hold nodes of integers.


Creating collections with generics is far easier than you might imagine. The simplest way to approach the problem is to build a type-specific collection, and then replace the type with the generic <T>.


Previous_Page_.gif Next_Page_.gif

Personal tools