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

Contravariance with in keyword in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Contravariance Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of contravariant interface assignment
What is the output of this C# program using contravariance with the in keyword?
C Sharp (C#)
using System;

interface IContravariant<in T>
{
    void Show(T item);
}

class Printer : IContravariant<object>
{
    public void Show(object item) => Console.WriteLine(item);
}

class Program
{
    static void Main()
    {
        IContravariant<string> printer = new Printer();
        printer.Show("Hello World");
    }
}
AHello World
BNo output
CRuntime error: InvalidCastException
DCompile-time error: Cannot convert IContravariant<object> to IContravariant<string>
Attempts:
2 left
💡 Hint
Remember that contravariance allows assignment from a less derived to a more derived generic type when using the in keyword.