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?✗ Incorrect
The
out keyword marks a generic type parameter as covariant, meaning it can only be used as a return type.Which of these is a valid use of a covariant type parameter marked with
out?✗ Incorrect
Covariant type parameters can only be used as return types, not as input parameters or writable fields.
Given
IEnumerable<out T>, can you assign IEnumerable<string> to IEnumerable<object>?✗ Incorrect
Covariance allows assigning
IEnumerable<string> to IEnumerable<object> safely.What error occurs if you use
out on a type parameter used as a method input?✗ Incorrect
The compiler enforces variance rules and will error if
out is used incorrectly.Which keyword is used for contravariance, the opposite of covariance?
✗ Incorrect
The
in keyword marks a generic type parameter as contravariant, allowing it to be used only as input.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.