What is covariance and contravariance, explain with example?
What is covariance and contravariance?
537
19-Jun-2025
ICSM Computer
24-Jun-2025Covariance and contravariance are concepts in C# that deal with type compatibility in generic interfaces, delegates, and method parameters/returns, especially when dealing with inheritance hierarchies.
They allow flexibility in assigning types that are related by inheritance — while maintaining type safety.
Covariance (Output flexibility —
out)outkeyword (for generic type parameters).IEnumerable<out T>or delegates.Example:
Contravariance (Input flexibility —
in)inkeyword (for generic type parameters).Action<in T>or interfaces likeIComparer<in T>.Example:
Summary Table
outIEnumerable<out T>inAction<in T>Real-World Use Case
Covariance
You can assign
IEnumerable<string>toIEnumerable<object>because strings are objects:Contravariance
A method that accepts
objectcan be used where a method acceptingstringis expected:When to Use