I'm working on a project and I saw a lot of code like this
public class ExemploCollection<T> { ... }
And I do not understand what this <T>
means.
What's the name of it, what do I look for? How does this work? What does this do?
I'm working on a project and I saw a lot of code like this
public class ExemploCollection<T> { ... }
And I do not understand what this <T>
means.
What's the name of it, what do I look for? How does this work? What does this do?
The context name of this is Generics , see the documentation .
T
is not a reserved word. T
, or any other given name, means "type parameter". Here's how:
T GetDefault<T>()
{
return default(T);
}
Note that the type return method is T
. With this method I can get the default value of any type this way:
GetDefault<int>(); // 0
GetDefault<string>(); // null
GetDefault<DateTime>(); // 01/01/0001 00:00:00
GetDefault<TimeSpan>(); // 00:00:00
.NET uses generics in object collections, example with List<T>
List<int> listaDeInteiros = new List<int>();
In this way you will have a list that will only accept integers, because the class is instantiated with type "T", in this case int
and the method that adds elements only accepts the type informed at the time of instantiating the class:
public class List<T> : ...
{
public void Add(T item);
}
Since we have a List<int>
, the Add
method will only accept integers.
In generics it is possible to limit the scope of type T
.
The following example only allows the use of the method with types that are classes
void FazAlgo<T>(T item) where T: class
{
}
The following example only allows you to use the method with types that are classes of type Circulo
or that inherit from Circulo
.
void FazAlgo<T>(T item) where T: Circulo
{
}
And there is also new()
, which if used this way, you can create a circle instance:
void FazAlgo<T>(T item) where T: Circulo, new()
{
T novoCirculo = new T();
}
Because T
is a type parameter, you can get the object Type
. And with the object Type
it is possible to do several things using reflection .
void FazAlgo<T>(T item) where T: class
{
Type type = typeof(T);
}
In a more complex example, to demonstrate what you can do with generics see the ToDictionary
method declaration, or any other Linq method.
public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector);
Notice that there is no T
. As I said earlier T
is not a reserved word. It is always a good practice to name type parameters with the T
prefix, as seen in the example above TKey
and TSource
.
You can name TFoo
if you want.