In my C# code I have the following hierarchies (I've ommited unnecessary keywords for clarity):
B : A
C : B
D : C
L<T> : K where T : C
M : L<D>
Now I get a casting error:
L<C> c = new M -- error
This passes ok:
L<D> a = new M -- ok
C b = new D -- ok
Why do I get this error on type L<C>
? Clearly M
, which is L<D>
can be followed back to L<C>
since D : C
.. but why is this an error? Also, if this error is correct, how do I avoid such errors?
UPDATE:
Also presenting runnable (i hope :)) code version:
public abstract class A {}
public class B : A {}
public class C : B {}
public class D : C {}
public abstract class K {}
public class L<T> : K where T : C {}
public class M : L<D> {}
// -- ok:
L<D> a = new M(); // ok
C b = new D(); // ok
// -- error:
L<C> c = new M(); // error
UPDATE 2
My vote for reopening is based on the fact that the thread marked as the "duplicate" of this question describes a little different situation with collections, where it is possible and clear how to cast between collection types because collection elements can be cast easily. However in my case this is not so and that solution won't work. So I vote for someone to either 1) give a proper solution 2) explain how can the solution from the referred thread be applied here 3) explain, why there is no solution.