0
0
C Sharp (C#)programming~5 mins

Contravariance with in keyword in C Sharp (C#) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AGenerates a new type parameter
BCovariance - allows more derived types as output
CContravariance - allows less derived types as input
DInvariant - no variance allowed
Which of these interfaces uses contravariance with in?
AIEnumerable&lt;T&gt;
BIComparer&lt;T&gt;
CIList&lt;T&gt;
DFunc&lt;T&gt;
Can a contravariant type parameter be used as a return type in a method?
ANo, never
BOnly if marked with <code>out</code>
CYes, always
DOnly in abstract classes
If a method expects IComparer<Cat>, which can you pass due to contravariance?
AIComparer&lt;Dog&gt;
BIComparer&lt;Tiger&gt;
CIComparer&lt;Cat&gt;
DIComparer&lt;Animal&gt;
What keyword marks covariance in C# generics?
Aout
Bin
Cref
Dvar
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.