Here's the code:
Base b = new Derived(); // Upcasting
// Some actions
Derived d = (Derived)b; // Downcasting
As I understand the reference is like stencil through which you're looking at some chunk of memory. And upcasting just narrows that stencil so you cannot access the members added with Derived class. And Downcasting here is expanding that stencil back again.
The question is:
Since no reference to derived part of type preserved, just the Base. Can it happen that some actions or activity of GC will erase or overwrite the chunk of memory that used to contain Derived members by the time the downcasting occured? In other words can downcasting Derived d = (Derived)b
fail?
That's a safe cast in the context. You've created
Derived
instance that's why it's always safe to treat Derived as Derived; no GC activity can spoil a part of the instance. Casting is a kind of treatment (I'm going to treat actualDerived
istance as beingBase
only: I've promised to call just a subset of methods, properties) and casting to itself is always safe.