Downcasting a generic type in C# 3.5

.net, c#, downcast, generics

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

Problem

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?

Original source