I’m new to C# and directly diving into modifying some code for a project I received. However, I keep seeing code like this :
class SampleCollection<T>
and I cannot make sense of what the
<T>
means nor what it is called.
If anyone would care to help me just name what this concept is called, I can search it online. However, I’m clueless as of now.
It is a Generic Type Parameter.
A generic type parameter allows you to specify an arbitrary type T to a method at compile-time, without specifying a concrete type in the method or class declaration.
For example:
reverses the elements in an array. The key point here is that the array elements can be of any type, and the function will still work. You specify the type in the method call; type safety is still guaranteed.
So, to reverse an array of strings:
Will produce a string array in
resultof{ "5", "4", "3", "2", "1" }This has the same effect as if you had called an ordinary (non-generic) method that looks like this:
The compiler sees that
arraycontains strings, so it returns an array of strings. Typestringis substituted for theTtype parameter.Generic type parameters can also be used to create generic classes. In the example you gave of a
SampleCollection<T>, theTis a placeholder for an arbitrary type; it means thatSampleCollectioncan represent a collection of objects, the type of which you specify when you create the collection.So:
creates a collection that can hold strings. The
Reversemethod illustrated above, in a somewhat different form, can be used to reverse the collection’s members.