0

I have a class with a generic Type:

class SomeClass<T>
{

}

And two classes -> one inherits fromt the other:

class Animal
{

}

class Lion : Animal
{

}

Now I want to create a variable of "SomeClass" with the base generic and give it an object witht the inherited type as generic type, like this:

    void Test()
    {
        SomeClass<Lion> someLion = new SomeClass<Lion>();

        SomeClass<Animal> someAnimal = someLion;    //Error line

    }

The error is:

Cannot implicitly convert type 'VitrasUI.SomeClass' to 'VitrasUI.SomeClass'

From my understanding I should be able to convert it this way, as it works with IEnumerables, too:

    void Test1()
    {
        IEnumerable<Lion> listLion = new List<Lion>();

        IEnumerable<Animal> listAnimal = listLion;
    }
  • 3
    Search for covariance and contravariance in C# – canton7 May 11 '20 at 09:49
  • Covariance doesn't work with generic classes, only with interfaces. `IEnumerable` declared as `IEnumerable`, you can make `SomeClass` interface and make it covariant against `T` – Pavel Anikhouski May 11 '20 at 09:50
  • (and only when declared as `ISomeInterface`) – canton7 May 11 '20 at 09:51
  • An `IEnumerable` is only for getting _out_ instances of `T`. With a `List` (or `IList`), you promise, that you can also put instances of `T` _in_. Now imagine a `List` being cast as a `List` and then putting an instance of `Lion` in there. That would cause some trouble. – Corak May 11 '20 at 10:18
  • 1
    I looked it all up and figured it out. Thanks for your quick responses. – Daniel Lichtenstern May 11 '20 at 10:39
  • Does this answer your question? [Why does C# (4.0) not allow co- and contravariance in generic class types?](https://stackoverflow.com/questions/2541467/why-does-c-sharp-4-0-not-allow-co-and-contravariance-in-generic-class-types) – pinkfloydx33 May 11 '20 at 12:27

1 Answers1

1

With the help of some comments I managed to figure it our quite fast.

What I did:

1) Understand Covariance and Contraviance

(this blog post was pretty easy to understand: http://tomasp.net/blog/variance-explained.aspx/)

2) I added an interface, of which the the abstract class (represented by SomeClass) inherits

3) I used the out keyword to mark the usage of the generic as covariant in the interface