Skip to main content
InterviewHubPRO
Section Overview
Q12

Question 12 of 50

Part 2: Concurrency, Zero-Allocation & Advanced Language Features (11 - 24)

24%
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 to IEnumerable<object>.
  • Contravariance (in): Allows you to use a more generic (base) type than originally specified (input only). Example: Action<object> can be assigned to Action<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);
}