What is covariance and contravariance, explain with example?
What is covariance and contravariance, explain with example?
Student
The Anubhav portal was launched in March 2015 at the behest of the Hon'ble Prime Minister for retiring government officials to leave a record of their experiences while in Govt service .
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