Downcasting generic type in C # 3.5

Why can I only raise the general, and not lower it?
How is it not clear to the compiler that if my constraint says where T : BaseClass and U from BaseClass, what is (U)objectOfTypeT really?

+4
source share
2 answers

Because it may be wrong. Consider this:

 class Base { } class A : Base { } class B : Base { } A temp1 = new A(); B temp2 = (B)temp1; // not valid 

Just because they use the same base class does not mean that you can give a type to another.

Note that you can get around this using the as operator:

 var result = objectOfTypeT as U; // this does not give any compilation error // but will result in a null reference if // objectOfTypeT cannot be converted to U 
+5
source

If I did not read this question correctly, you could:

 class A:BaseClass{} class B:BaseClass{} 

For T = A and U = B, both restrictions are happy, but distinct from T to U are clearly invalid.

If U is another class, then it applies anyway; T, as you know, is not in the same chain as U unless you specify it in the constraints (general constraints may include other general arguments of the type, if that helps).

+2
source

All Articles