Question

Why can I only upcast a generic and not downcast it?
How is it not clear to the compiler that if my constraint says where T : BaseClass and U is derived from BaseClass that (U)objectOfTypeT is valid?

Was it helpful?

Solution

Because it might not be valid. Consider this:

class Base { }
class A : Base { }
class B : Base { }

A temp1 = new A();
B temp2 = (B)temp1; // not valid

Just because they share the same base class does not mean that you can typecast one to the other.

Note that you can get around this by 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

OTHER TIPS

Unless I read the question wrong, you could have:

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

With T=A and U=B, both constraints are happy, but the cast from T to U is clearly invalid.

If U is just another class, then the same still applies; the T is not known to be in the same chain as U unless you state it in the constraints (generic constraints can involve other generic type arguments, if it helps).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top