Why is it not safe to convert an instance of a base type to a derived object / reference type

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 figure out why a cast / convert conversion from a base type to a reference to a derived type is NOT considered type safe?

Technically, the D object contains all of B's ​​functions, so it should act as a reference to its underlying instance. Shouldn't the exception be the other way around? for example line 1 should fail, but not line 2.

Is type safety an image only when we try to use / convert from a type to a completely different type? And in case an instance of the base type for the derived type is not allowed and the other way is allowed just because by design?

Thank!

Kartikeyan

+3


source to share


1 answer


You can appoint new D

B

because it D

has everything B

and also some additional things. Thus, it is safe to treat it as a B

.

Otherwise, a new B

doesn't have everything a is D

, so if you did a specific function D

or accessed a specific property / member D

, it wouldn't work out spectacularly.



So this assignment / listing is not safe or valid.

+3


source







All Articles