Ravi Vishwakarma is a dedicated Software Developer with a passion for crafting efficient and innovative solutions. With a keen eye for detail and years of experience, he excels in developing robust software systems that meet client needs. His expertise spans across multiple programming languages and technologies, making him a valuable asset in any software development project.
ICSM Computer
16-Jun-2025Covariance 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: