C# & CLR Internals (50 Qs)•Part 2: Concurrency, Zero-Allocation & Advanced Language Features (11 - 24)
How does Generics Covariance (out) and Contravariance (in) work in C#?
senior LevelCode ExampleTypeScript
In Simple Words: Variance defines whether generic types with polymorphic relationships can be substituted for one another.
- Covariance (
out): Allows you to use a more derived type than originally specified (output only). Example:IEnumerable<string>can be assigned toIEnumerable<object>. - Contravariance (
in): Allows you to use a more generic (base) type than originally specified (input only). Example:Action<object>can be assigned toAction<string>.
csharp
// Covariant interface (out = return type only):
public interface IProducer<out T> {
T Produce();
}
// Contravariant interface (in = argument type only):
public interface IConsumer<in T> {
void Consume(T item);
}