Explain the difference between covariance and contravariance.
Ask by ICSM Computer
Updated 16 Jun 2025
Covariance vs Contravariance in C#
These concepts apply to generic type parameters and determine how you can use inheritance in delegates, interfaces, and generics.
1. Covariance (output)
outkeywordExample: Covariance with
IEnumerable<out T>Here:
stringinherits fromobjectIEnumerable<out T>is covariant, so you can assign a more derived type (IEnumerable<string>) to a base type (IEnumerable<object>)Custom Example:
2. Contravariance (input)
inkeywordExample: Contravariance with
Action<in T>stringis a subtype ofobjectAction<in T>is contravariant, soAction<object>can be assigned toAction<string>Custom Example:
Summary Table
outinstring→object)object→string)IEnumerable<out T>IComparer<in T>,Action<in T>Real-Life Analogy
Catlike anAnimalwhen returning it from a method.”Animalto a method that expects aCatbecause the method knows how to handle anyAnimal.”Let me know if you'd like: