Generics in C#

Generics were added to version 2.0 of the C# language and the common language runtime (CLR). Generics introduce to the .NET Framework the concept of type parameters, which make it possible 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. For example, by using a generic type parameter T you can write a single class that other client code can use without incurring the cost or risk of runtime casts or boxing operations, as shown here:

// Declare the generic class.
public class GenericList
{
    void Add(T input) { }
}
class TestGenericList
{
    private class ExampleClass { }
    static void Main()
    {
        // Declare a list of type int.
        GenericList list1 = new GenericList();

        // Declare a list of type string.
        GenericList list2 = new GenericList();
        // Declare a list of type ExampleClass.
        GenericList list3 = new GenericList();
    }
}

Ebook Download
View all
Learn
View all