internal class B { }
internal class D : B { }
class Program {
static void Main(string[] args) {
B dToB = new D();//will execute successfully. - line 1
D bToD = (D) new B(); //will fail at runtime. - line 2
}
}
I couldn't understand why the cast/convert from base type instance to derived type reference is NOT considered type safe?
Technically the object D contains all the features of B so it should be able act as a reference to it's base instance. Shouldn't the exception be other way around ? like, line 1 should fail but not line 2.
Is type safety comes into picture only when we try to cast/convert from a type to a totally different type? And in case of base type instance to derived type reference is NOT allowed and the other way is allowed just because by design ?
Thanks!
Karthikeyan