November 14, 2003
@ 03:17 AM

[Via Dan Fernandez]

Introduction to C# Generics

Some snippets from the article for introduction ...

Generics allow you to define type-safe data structures, without committing to actual data types. This results in a significant performance boost and higher quality code, because you get to reuse data processing algorithms without duplicating type-specific code.

Consider an everyday data structure such as a stack, providing the classic Push() and Pop() methods. When developing a general-purpose stack, you would like to use it to store instances of various types. Under C# 1.1, you have to use an Object-based stack, meaning that the internal data type used in the stack is an amorphous Object, and the stack methods interact with Objects:

 public class Stack {
object[] m_Items;
public void Push(object item)
{...}
public object Pop()
{...}
}

Generics allow you to define type-safe classes without compromising type safety, performance, or productivity. You implement the server only once as a generic server, while at the same time you can declare and use it with any type. To do that, use the and > brackets, enclosing a generic type parameter. For example, here is how you define and use a generic stack:

 public class Stack {
T[] m_Items;
public void Push(T item) {...}
public T Pop() {...}
}
Stack stack = new Stack();
stack.Push(1);
stack.Push(2);
int number = stack.Pop();
On the surface C# generics look very similar to C++ templates, but there are important differences in the way they are implemented and supported by the compiler. As you will see later in this article, this has significant implications on the manner in which you use generics. Compared to C++ templates, C# generics provide enhanced safety but are also somewhat limited in capabilities.