Skip to content
Sharp

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 what T can 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 like IEnumerable<T>; in T (contravariant) for consumers like Action<T>.

Questions

  1. What does the constraint where T : new() require?Multiple choiceEasy
  2. What does this program print?What does this code output?Medium
  3. Complete the statements about generic variance.Drop-down clozeHard