Generics interview questions
Type parameters, constraints, variance.
3 questions with answers and explanations · 2 flashcards
Key ideas
- Generics give compile-time type safety and avoid boxing for value types.
- Constraints (
where T : class,struct,new(), a base type, an interface) limit whatTcan be and unlock members. - Each closed generic type (
List<int>,List<string>) is its own type with its own static fields. - Variance:
out T(covariant) for producers likeIEnumerable<T>;in T(contravariant) for consumers likeAction<T>.