3

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

Silverdust
  • 1,503
  • 14
  • 26
  • Asked a few times: [why-doesnt-c-sharp-do-simple-type-inference-on-generics](http://stackoverflow.com/questions/4503603/why-doesnt-c-sharp-do-simple-type-inference-on-generics) or [why-generics-of-derived-classes-produces-non-derived-classes](http://stackoverflow.com/questions/19431491/why-generics-of-derived-classes-produces-non-derived-classes) – nawfal Jul 10 '14 at 06:12

1 Answers1

5

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>
BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117