![]() |
|
Generics in C#, Free online C# Programming Tutorial... |
| Lessons | C# Generics |
|
The following example illustrates the use of generics in C#: public class GenericContainer <T>
{
private T element;
public GenericContainer(T element)
{
this.element =element;
}
public T getElement()
{
return this.element;
}
}
The instantiation of objects from the above GenericContainer class is pretty simple:GenericContainer<int> a = new GenericContainer<int>(34); // Generic Container of int type GenericContainer<string> a = new GenericContainer<string>(“Hello World”); // Generic Container of string type GenericContainer<double> a = new GenericContainer<double>(3.04); // Generic Container of double type From the above GenericContainer class you could instantiate any number of containers, each having the capability to store a different type of element. While the example is far from practical, it does illustrate the basic idea of generics. Note that you can have any number of type parameters in a generic class as per your needs. Each additional type parameter has to have a different name. We used T in the above example and if we needed to have an additional type parameter we could have named it as S, for example.
Next >>> Lesson No. 20: C# Interfaces, Boxing, new
|