Compile-time and runtime casting c#

后端 未结 2 536
-上瘾入骨i
-上瘾入骨i 2020-11-27 20:44

I was wondering why some casts in C# are checked at compile-time whereas in other cases the responsibility is dumped on CLR. Like above both are incorrect but handled in a d

2条回答
  •  佛祖请我去吃肉
    2020-11-27 21:50

    • Upcasts can be checked at compile time - the type system guarantees that the cast succeeds.
    • Downcasts cannot (in general) be checked at compile time, so they are always checked at runtime.
    • Unrelated types cannot be cast to each other.

    The compiler considers only the static types. The runtime checks the dynamic (runtime) type. Looking at your examples:

    Other x = new Other();
    Derived d = (Derived)x; 
    

    The static type of x is Other. This is unrelated to Derived so the cast fails at compile time.

    Base x = new Base();
    Derived d = (Derived)x; 
    

    The static type of x is now Base. Something of type Base might have dynamic type Derived, so this is a downcast. In general the compiler can't know from the static type of x if it the runtime type is Base, Derived, of some other subclass of Base. So the decision of whether the cast is allowed is left to the runtime.

提交回复
热议问题