Generics are an extension to the type system whereby structs, classes, interfaces, delegates, and methods can be parameterized with types. For example, generic types like List<T> is a generator for constructed types like List<string> and List<Person>. All the collections in the .NET Framework library used by C# are available in generic form. They include Dictionary, Stack, Queue, and List, plus variations on them. There are also generic methods such as Sort and BinarySearch. These require the types they are working on to implement the IComparer interface so that comparisons between elements can be done correctly.

To specify a generic type or method, use the generic parameters in angle brackets, as in <T> or <T, P>. The generic type can be used to specify further generic elements, again using the <T> format, or it can be used normally as a type, as in T.

To construct an actual type or method from a generic one, supply actual types for each of the generic parameters, as in <string>.

cf. C# Language Specification Version 3.0, September 2007, Section 10.1.3

Leave a Reply