Search code examples
c#contravariance

understanding contravariance in C#


I am learning on contravariance and tried the following to absorb the concept:

interface B<T>
{
    T h();
}

public class SomeOtherClass<T> : B<T>
{
    public T h()
    {
        return default(T);
    }
}

public class Trial
{
    static void Main()
    {
        SomeOtherClass<Derived> h = new SomeOtherClass<Derived>();      
        Base b = h.h();     
    }
}

I was expecting that this code would error out at the last statement and thought making T contravariant would fix it. However, this works as is. Makes me wonder where contravariance finds applicability?


Solution

  • Generics varriance is used in interface and delgates

    Change your code to below and you will start getting the error

    public class Trial
    {
        static void Main()
        {
            B<Derived> h = new SomeOtherClass<Derived>();      
            B<Base> b = h; // you will get compilation error until you add out keyword in interface B     
        }
    }
    

    Here out (Contravariant) keyword is way to tell compiler that instance of B is safe to be considered b