Scenario:
class A { }
class B : A { }
class C where T: A { }
Question
Why cant C<
Because C<A>
is not C<B>
The thing is; if you could do
C<A> myA = new C<B>();
myA.Add(new A());
You'd have a problem, since B is A
, but not A is B
Use co-variant if you need to do this, and because co-variant just work only with interface and delegate, so define an interface with the magic word out instead of class:
interface IC<out T> where T : A
{
}
So, you can assign like you want:
class CA : IC<A>
{}
class CB : IC<B>
{ }
IC<A> x = new CA();
IC<B> y = new CB();
x = y;
Why cant C<A> = C<B> when B is a subclass of A?
B
is subclass of A
, but C<B>
not a subclass of C<A>
. There is no assignment compatibility between C<B>
and C<A>
.
What you are asking for is Covariance and Contravariance in Generics which is only applicaple for interfaces and delegates. You can check this
You can do the following in Framework >= 4:
interface IC<out T> where T : A
class C<T> : IC<T> where T : A
IC<A> ica = new C<B>();
For your case you should extract an interface for class C