Udostępnij za pośrednictwem


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 Introduction to Generics (C# Programming Guide), 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 Generics in the Run Time (C# Programming Guide).

Type Parameter Naming Guidelines

  • 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.

    public interface ISessionChannel<TSession> { /*...*/ }
    public delegate TOutput Converter<TInput, TOutput>(TInput from);
    public class List<T> { /*...*/ }
    
  • Consider using T as the type parameter name for types with one single letter type parameter.

    public int IComparer<T>() { return 0; }
    public delegate bool Predicate<T>(T item);
    public struct Nullable<T> where T : struct { /*...*/ }
    
  • Do prefix descriptive type parameter names with "T".

    public interface ISessionChannel<TSession>
    {
        TSession Session { get; }
    }
    
  • Consider indicating constraints placed on a type parameter in the name of parameter. For example, a parameter constrained to ISession may be called TSession.

See Also

Concepts

C# Programming Guide

Reference

Generics (C# Programming Guide)

Differences Between C++ Templates and C# Generics (C# Programming Guide)

System.Collections.Generic