Generic Classes
A generic class is a container that can hold any type you choose, like a box labeled 'for shoes' or 'for toys'. You write it once and use it with many types safely.
In this page:
Syntax
class ClassName<T>
{
private T value;
public void Set(T value) { this.value = value; }
public T Get() { return value; }
}
ClassName<type> variable = new ClassName<type>();
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Forgetting the type argument, such as
Box b = new Box();forBox<T>, which is a compile error. - Assuming
Tsupports operators such as+without a constraint, which is a compile error. - Using
new T()without thenew()constraint.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: