How do you declare a generic class with a type parameter, and how do you instantiate it with a specific type?
Short answer
Add ` ` (or any name, conventionally T, TKey, TValue, etc.) after the class name to declare a type parameter usable throughout the class body; specify the concrete type in angle brackets when creating an instance with 'new'.
Advertisement
AModel answer
Add `<T>` (or any name, conventionally T, TKey, TValue, etc.) after the class name to declare a type parameter usable throughout the class body; specify the concrete type in angle brackets when creating an instance with 'new'.
public class Box<T> {
private T _value;
public Box(T value) { _value = value; }
public T GetValue() => _value;
}
Box<int> intBox = new Box<int>(42);
Box<string> stringBox = new Box<string>("hello");Real-world example
Building a reusable Box<T>, Repository<T>, or Cache<T> class usable with any specific entity type.
Likely follow-ups
- Can a generic class have MULTIPLE type parameters, like Dictionary<TKey, TValue>?
Related topics