Generics · interview question
Complete the statements about generic variance.
Drop-down clozeHard
Choose the option that best completes each blank.
`IEnumerable<out T>` is , so an `IEnumerable<string>` can be assigned to a variable of type . `Action<in T>` is , so an `Action<object>` can be used where an `Action<string>` is expected.
Answer and explanation
Correct answer
IEnumerable<out T> is covariant, so an IEnumerable<string> can be assigned to a variable of type IEnumerable<object>. Action<in T> is contravariant, so an Action<object> can be used where an Action<string> is expected.
Why
Covariance (out) suits producers; contravariance (in) suits consumers. Variance applies only to interfaces and delegates, and only to reference-type arguments.
References
Test yourself on Generics
A free test with instant, explained results. No account needed.