|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer|
Generic Type Parameters (C# Programming Guide)
In a generic type or method definition, a type parameters is a placeholder for a specific type that a client specifies when they instantiate a variable of the generic type. A generic class, such as
GenericList<T> listed in , cannot be used as-is because it is not really a type; it is more like a blueprint for a type. To use
GenericList<T>, client code must declare and instantiate a constructed type by specifying a type argument inside the angle brackets. The type argument for this particular class can be any type recognized by the compiler. Any number of constructed type instances can be created, each one using a different type argument, as follows:
GenericList<float> list1 = new GenericList<float>(); GenericList<ExampleClass> list2 = new GenericList<ExampleClass>(); GenericList<ExampleStruct> list3 = new GenericList<ExampleStruct>();
In each of these instances of
GenericList<T>, every occurrence of
T in the class will be substituted at run time with the type argument. By means of this substitution, we have created three separate type-safe and efficient objects using a single class definition. For more information on how this substitution is performed by the CLR, see .
Do name generic type parameters with descriptive names, unless a single letter name is completely self explanatory and a descriptive name would not add value.
Consider using T as the type parameter name for types with one single letter type parameter.
Do prefix descriptive type parameter names with “T”.
Consider indicating constraints placed on a type parameter in the name of parameter. For example, a parameter constrained to
ISessionmay be called