Generics let you write type-safe code parameterized by types—List<T>, Dictionary<TKey, TValue>, and your own Stack<T>. Unlike C++ templates, C# generics are reified at runtime for reference types with shared JIT code where possible.
Generic class
class Box<T> {
public T Value { get; }
public Box(T value) => Value = value;
}
Constraints
static T Max<T>(T a, T b) where T : IComparable<T> {
return a.CompareTo(b) >= 0 ? a : b;
}
Constraints limit T to types with required members—catch errors at compile time, similar to bounded generics in Java.
Important interview questions and answers
- Q: Generics vs object boxes?
A: Generics avoid casts and boxing for value types—better performance and type safety. - Q: Covariance?
A:IEnumerable<out T>allows substituting derived types in read-only scenarios.
Self-check
- What keyword constrains T to have CompareTo?
- Why not use ArrayList of object today?
Tip: Generic types are reified at runtime in .NET—unlike Java erasure, List<int> and List<string> are distinct types.
Interview prep
- Generics vs templates?
C# generics are reified at runtime with shared JIT code for reference types; C++ templates instantiate per type at compile time.
- where T : constraint?
Restricts type parameters—e.g.
where T : class,where T : new(), or interface requirements.