D J
D J

Reputation: 7028

How to support Co Variance generics here

Although I have seen the examples, but still I am confused how to make it working. I need to support some variance in generics.

public interface I1 { }

public class BaseClass<U> : List<U>
    where U : I1 {}

public class Class1 : I1 { }

public class DerivedClass : BaseClass<Class1>
{
}

public class TestMain
{
    public void StartUsing()
    {
        /*Compiler error,              
         Cannot implicitly convert type 'DerivedClass' to 'BaseClass<I1>'*/
        BaseClass<I1> baseObj = new DerivedClass();
    }
}

What is the mistake here.

Upvotes: 1

Views: 54

Answers (1)

cuongle
cuongle

Reputation: 75306

First, List<U> is invariant, you cannot make BaseClass covariant if inheriting from List<U>.

Second, co-variant only supports interface, so you have to change BaseClass to interface instead of class.

Third, use out keyword to make an interface as covariant. So, in your case, you can declare:

public interface I1 { }

public interface IBaseClass<out U> : IEnumerable<U> where U : I1 { }

public class Class1 : I1 { }

public class DerivedClass : IBaseClass<Class1>
{
}

Then, it works:

IBaseClass<I1> baseObj = new DerivedClass();

Upvotes: 1

Related Questions