It is a generic type parameter, see Generics documentation.
T
is not a reserved keyword. T
, or any given name, means a type parameter. Check the following method (just as a simple example).
T GetDefault<T>()
{
return default(T);
}
Note that the return type is T
. With this method you can get the default value of any type by calling the method as:
GetDefault<int>(); // 0
GetDefault<string>(); // null
GetDefault<DateTime>(); // 01/01/0001 00:00:00
GetDefault<TimeSpan>(); // 00:00:00
.NET uses generics in collections, ... example:
List<int> integerList = new List<int>();
This way you will have a list that only accepts integers, because the class is instancited with the type T
, in this case int
, and the method that add elements is written as:
public class List<T> : ...
{
public void Add(T item);
}
Some more information about generics.
You can limit the scope of the type T
.
The following example only allows you to invoke the method with types that are classes:
void Foo<T>(T item) where T: class
{
}
The following example only allows you to invoke the method with types that are Circle
or inherit from it.
void Foo<T>(T item) where T: Circle
{
}
And there is new()
that says you can create an instance of T
if it has a parameterless constructor. In the following example T
will be treated as Circle
, you get intellisense...
void Foo<T>(T item) where T: Circle, new()
{
T newCircle = new T();
}
As T
is a type parameter, you can get the object Type
from it. With the Type
you can use reflection...
void Foo<T>(T item) where T: class
{
Type type = typeof(T);
}
As a more complex example, check the signature of ToDictionary
or any other Linq method.
public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector);
There isn't a T
, however there is TKey
and TSource
. It is recommended that you always name type parameters with the prefix T
as shown above.
You could name TSomethingFoo
if you want to.