Contravariance lets you use a more general type than originally specified. It helps when you want to pass a less specific type safely.
Contravariance with in keyword in C Sharp (C#)
interface IExample<in T> { void DoSomething(T item); }
The in keyword before the generic type parameter means contravariance.
Contravariant types can only be used as input (method parameters), not as output (return types).
in to allow contravariance on T.interface IConsumer<in T> { void Consume(T item); }
string is more specific than object, and in enables contravariance.IConsumer<object> consumer = new Consumer<string>();Here, IConsumer<in T> allows assigning IConsumer<object> (implemented by ObjectConsumer) to IConsumer<string> because of contravariance. The method Consume accepts an object, but the variable is typed as IConsumer<string>.
using System; interface IConsumer<in T> { void Consume(T item); } class ObjectConsumer : IConsumer<object> { public void Consume(object item) { Console.WriteLine($"Consumed object: {item}"); } } class Program { static void Main() { IConsumer<string> consumer = new ObjectConsumer(); consumer.Consume("Hello World"); } }
Contravariance only works with input parameters, not return types.
You cannot use the contravariant type parameter to return values from methods.
Contravariance helps make your code more flexible and reusable.
Use in keyword to declare contravariant generic type parameters.
Contravariant types can accept more general types safely.
It applies only to input positions like method parameters.
Practice
What does the in keyword specify when used in a generic interface declaration like IComparer?
Solution
Step 1: Understand the role of
Theinkeyword in genericsinkeyword declares a generic type parameter as contravariant, meaning it can accept arguments of less derived types safely.Step 2: Contrast with covariance
Covariance (usingout) allows returning more derived types, while contravariance (usingin) allows accepting less derived types as input.Final Answer:
It marks the type parameter as contravariant, allowing it to accept less derived types. -> Option BQuick Check:
inmeans contravariant = It marks the type parameter as contravariant, allowing it to accept less derived types. [OK]
- Confusing 'in' with covariance (out keyword)
- Thinking 'in' restricts to value types
- Assuming 'in' applies to return types
Which of the following is the correct syntax to declare a contravariant generic interface IProcessor with type parameter T?
?
Solution
Step 1: Identify contravariant syntax
Contravariance usesinkeyword before the type parameter in interface declaration.Step 2: Check method usage
Contravariant type parameters can only be used as input parameters, not as return types. So method must acceptTas parameter, not return it.Final Answer:
interface IProcessor<in T> { void Process(T item); } -> Option AQuick Check:
Contravariant =in+ input parameter only = interface IProcessor<in T> { void Process(T item); } [OK]
- Using 'out' instead of 'in' for contravariance
- Returning type T in contravariant interface
- Omitting 'in' keyword
Consider the following code snippet:
interface IConsumer { void Consume(T item); }
class Animal { }
class Dog : Animal { }
IConsumer<Animal> animalConsumer = new Consumer();
IConsumer<Dog> dogConsumer = animalConsumer;What will happen when this code runs?
Solution
Step 1: Understand contravariance assignment
Contravariance allows assigningIConsumer<Animal>toIConsumer<Dog>becauseDogis more derived thanAnimal.Step 2: Check code behavior
The assignmentIConsumer<Dog> dogConsumer = animalConsumer;is valid and compiles because ofinkeyword onT.Final Answer:
It compiles and runs successfully due to contravariance. -> Option CQuick Check:
Contravariance allows assignment from base to derived = It compiles and runs successfully due to contravariance. [OK]
- Thinking assignment is invalid due to type mismatch
- Confusing contravariance with covariance
- Expecting runtime errors
Given this interface declaration:
interface IHandler { void Handle(T item); }Which of the following code snippets will cause a compile-time error?
?
Solution
Step 1: Recall contravariance assignment rules
Contravariance allows assignment from less derived to more derived generic types, e.g.,IHandler<Animal>toIHandler<Dog>.Step 2: Analyze each option
IHandler<object> handler = new Handler<string>();tries to assignIHandler<string>toIHandler<object>, which is from more derived to less derived generic types, invalid for contravariance.Final Answer:
IHandler<object> handler = new Handler<string>(); -> Option AQuick Check:
Contravariance disallows assigning derived generic to base generic =IHandler<object> handler = new Handler<string>();[OK]
- Assigning derived generic to base generic incorrectly
- Confusing contravariance with covariance
- Ignoring compile-time type safety
You have these interfaces and classes:
interface IProcessor { void Process(T item); }
class Vehicle { }
class Car : Vehicle { }
class VehicleProcessor : IProcessor<Vehicle> {
public void Process(Vehicle item) { Console.WriteLine("Processing vehicle"); }
}Which assignment is valid and why?
?
Solution
Step 1: Understand contravariance assignment direction
Contravariance allows assigningIProcessor<Vehicle>toIProcessor<Car>becauseCaris derived fromVehicle.Step 2: Evaluate each option
IProcessor<Car>carProcessor = new VehicleProcessor(); // Valid because of contravariance assignsVehicleProcessor(implementsIProcessor<Vehicle>) toIProcessor<Car>variable, which is valid due to contravariance.Final Answer:
IProcessor<Car> carProcessor = new VehicleProcessor(); // Valid because of contravariance -> Option DQuick Check:
Contravariance allows base to derived assignment = IProcessor<Car> carProcessor = new VehicleProcessor(); // Valid because of contravariance [OK]
- Confusing covariance and contravariance directions
- Trying to assign interface instances incorrectly
- Ignoring inheritance hierarchy in assignments
Ready to prove it?
Pass the test and this pattern moves unknown
