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

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

Choose your learning style9 modes available
Recall & Review
beginner
What does the out keyword mean in C# interfaces?
The out keyword marks a generic type parameter as covariant, allowing a method to return a more derived type than originally specified. It enables safe type substitution from a less derived type to a more derived type.
Click to reveal answer
intermediate
Why can't you use out keyword on method input parameters?
Because covariance only applies to output (return) types, using out on input parameters would break type safety. Input parameters must be contravariant (using in) or invariant.
Click to reveal answer
beginner
Example: What does this interface mean?
interface IEnumerable<out T> { IEnumerator<T> GetEnumerator(); }
It means IEnumerable is covariant in T. You can use IEnumerable<Base> where IEnumerable<Derived> is expected, because T is marked with out.
Click to reveal answer
intermediate
What happens if you try to use out on a generic type parameter that appears as a method input?
The compiler will give an error because covariance requires the type parameter to be used only in output positions. Using it as input breaks the covariance rule.
Click to reveal answer
beginner
How does covariance with out improve code flexibility?
It allows you to assign objects of more derived generic types to variables of less derived generic types safely, reducing the need for explicit casts and increasing code reuse.
Click to reveal answer
What does the out keyword do in a generic interface?
ADisables generic type usage
BAllows the generic type to be used only as a method input (contravariance)
CMakes the generic type invariant
DAllows the generic type to be used only as a return type (covariance)
Which of these is a valid use of a covariant type parameter marked with out?
AAs a method return type
BAs a method input parameter
CAs a field type for writing
DAs a method parameter passed by ref
Given IEnumerable<out T>, can you assign IEnumerable<string> to IEnumerable<object>?
ANo, because generics are invariant by default
BNo, because string is not object
CYes, because of covariance
DYes, but only with a cast
What error occurs if you use out on a type parameter used as a method input?
AWarning only
BCompiler error: Invalid variance usage
CNo error, it's allowed
DRuntime exception
Which keyword is used for contravariance, the opposite of covariance?
Ain
Bout
Cref
Dvar
Explain covariance in C# and how the out keyword enables it.
Think about how you can safely substitute types when returning values.
You got /4 concepts.
    Describe a scenario where covariance with out is useful in a real program.
    Consider collections of objects and how you might want to treat them as collections of their base type.
    You got /4 concepts.