4
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

nvoigt
  • 75,013
  • 26
  • 93
  • 142
Karthik
  • 127
  • 2
  • 9

1 Answers1

3

You can assign a new D to a B because D has everything B does, plus some extra stuff. Thus, it is safe to treat it like a B.

Going the other way, a new B does not have everything a D has, so if you executed a D specific function, or accessed a D specific property/member, it would fail spectacularly.

Thus, this assignment/cast is not safe, or valid.

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
  • 1
    got it thanks! I was missing the fact that the underlying type's runtime type is B but the reference is D and when we try to access D's member on B's instance it will fail. – Karthik Sep 05 '14 at 19:10