Covariance 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)
Allows a more derived type to be used than originally specified.
Applies to return types (output).
Declared using the out keyword (for generic type parameters).
Common in interfaces like IEnumerable<out T> or
delegates.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Covariance 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