Chapter 9. Generics

One of the new features in the .NET Framework (beginning with version 2.0) is the support of generics in Microsoft Intermediate Language (MSIL). Generics use type parameters, which allow you to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code. Generics enable developers to define type-safe data structures, without binding to specific fixed data types at design time.

Generics are a feature of the IL and not specific to C# alone, so languages such as C# and VB.NET can take advantage of them.

This chapter discusses the basics of generics and how you can use them to enhance efficiency and type safety in your applications. Specifically, you will learn:

  • Advantages of using generics

  • How to specify constraints in a generic type

  • Generic interfaces, structs, methods, operators, and delegates

  • The various classes in the .NET Framework class library that support generics

Understanding Generics

Let's look at an example to see how generics work. Suppose that you need to implement your own custom stack class. A stack is a last-in, first-out (LIFO) data structure that enables you to push items into and pop items out of the stack. One possible implementation is:

public class MyStack
    private int[] _elements;
    private int _pointer;

    public MyStack(int size)
        _elements = new int[size];
_pointer = 0; } public void Push(int item) { if (_pointer > _elements.Length - 1) { throw new Exception("Stack ...

Get C# 2008 Programmer's Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.