Generic Classes
In this page:
Generic Classes
A generic class uses a type parameter, like Box<T>, so the same class definition can work with any type while staying fully type-safe. The actual type is supplied when the class is instantiated, such as Box<int> or Box<string>. This avoids duplicating the same class for every type you need it to hold.
Note: Generic type parameters are conventionally named T, or something descriptive like TKey/TValue for multiple parameters.
Example: Generic Classes
using System;
class Box<T>
{
private T value;
public void Set(T value)
{
this.value = value;
}
public T Get()
{
return value;
}
}
class Program
{
static void Main(string[] args)
{
Box<int> intBox = new Box<int>();
intBox.Set(42);
Console.WriteLine(intBox.Get());
Box<string> strBox = new Box<string>();
strBox.Set("hello");
Console.WriteLine(strBox.Get());
}
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: