Featured post
.net - Compile-time and runtime casting c# -
i wondering why casts in c# checked @ compile-time whereas in other cases responsibility dumped on clr. above both incorrect handled in different way.
class base { } class derived : base { } class other { }  static void main(string[] args) {     derived d = (derived)new base();     //runtime       invalidcastexception     derived d = (derived)new other();    //compile-time  cannot convert type... } while reading "c# in depth" i've found information on topic autor says:
   "if compiler spots it’s impossible cast work, it’ll trigger compilation error—and if it’s theoretically allowed incorrect @ execution time, clr throw exception."
does 'theoretically' mean connected inheritance hierarchy (some affinity between objects ?) or compiler's internal business?
- upcasts can checked @ compile time - type system guarantees cast succeeds.
- downcasts cannot (in general) checked @ compile time, checked @ runtime.
- unrelated types cannot cast each other.
the compiler considers static types. runtime checks dynamic (runtime) type. looking @ examples:
other x = new other(); derived d = (derived)x;  the static type of x other. unrelated derived cast fails @ compile time.
base x = new base(); derived d = (derived)x;  the static type of x base. of type base might have dynamic type derived, downcast. in general compiler can't know static type of x if runtime type base, derived, of other subclass of base. decision of whether cast allowed left runtime.
- Get link
- X
- Other Apps
Comments
Post a Comment