Question

It looks to me like I am having an understanding problem with covariance in c#. If I have the following classes:

class a {
}

class b : a {
}

class A<T> where T: a {
}

class B<T> : A<T> {
}

class C : A<b> {
}

And now I do:

A<a> t1 = new B<b>();
A<a> t2 = new C();

Neither of those work - but why?? Doesn't this article from Microsoft propose, that exactly this should be working? http://msdn.microsoft.com/de-de/library/dd799517(v=vs.110).aspx

Why isn't this very simple example not working?

Best regards

Was it helpful?

Solution

Covariance works like you describe, but there is one important piece:

A generic class is only covariant if it inherits from an interface marked with the "out" keyword on the covariant generic parameter.

There are a bunch of rules on how you can use this, see MSDN for details.

You aren't inheriting a covariant interface, so your derived assignments will break.

You need something like:

IGeneric<out T>
{
}

class a<T> : IGeneric<T>
{
}

and so on. Your assignments should work as long as it looks like:

IGeneric<Base> = a<Derived>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top