Recall & Review
beginner
What does the
in keyword mean in C# generic interfaces?The
in keyword marks a generic type parameter as contravariant, allowing you to use a less derived type than originally specified. It means you can pass a more general type where a more specific type is expected.Click to reveal answer
beginner
Explain contravariance in simple terms.
Contravariance lets you use a more general type instead of a more specific one. For example, if a method expects a
Cat, contravariance lets you pass an Animal instead, because Animal is more general than Cat.Click to reveal answer
intermediate
Which C# interfaces commonly use the
in keyword for contravariance?Interfaces like
IComparer<T> and IEqualityComparer<T> use the in keyword to allow contravariance on their generic type parameters.Click to reveal answer
intermediate
Can you use the
in keyword on generic type parameters used as return types?No. The
in keyword can only be used on generic type parameters that are used as input (method parameters). It cannot be used on return types because contravariance applies only to input positions.Click to reveal answer
intermediate
What is the difference between covariance and contravariance in C#?
Covariance (marked with
out) allows using a more derived type than originally specified, usually for return types. Contravariance (marked with in) allows using a less derived type, usually for input parameters.Click to reveal answer
What does the
in keyword specify in a generic interface?✗ Incorrect
The
in keyword marks a generic type parameter as contravariant, meaning it accepts less derived types as input.Which of these interfaces uses contravariance with
in?✗ Incorrect
IComparer<T> uses in to allow contravariance on its type parameter.Can a contravariant type parameter be used as a return type in a method?
✗ Incorrect
Contravariant type parameters (marked with
in) cannot be used as return types.If a method expects
IComparer<Cat>, which can you pass due to contravariance?✗ Incorrect
Contravariance allows passing
IComparer<Animal> where IComparer<Cat> is expected because Animal is less derived than Cat.What keyword marks covariance in C# generics?
✗ Incorrect
The
out keyword marks covariance, allowing more derived types as output.Describe contravariance and how the
in keyword enables it in C# generics.Think about how you can use a more general type where a specific type is expected.
You got /4 concepts.
Explain why contravariant type parameters cannot be used as return types in methods.
Consider the direction of data flow for contravariant types.
You got /4 concepts.