can I cast a superclass into a subclass?
I thought this would be possible but I get told "Unable to cast object of type Base into type Derived." The Base class is defined in another assembly (not my own), while the Derived class is my own. Is this as expected, or am I doing something wrong?
KeironPosted Aug 8, 2007, 8:53 AM
SamPosted Aug 8, 2007, 8:25 AM
Hi Keiron,
You can cast a variable of a superclass in to a subclass (down-cast) if the superclass variable actually hold a reference to an instance of a the derived class.
i.e
Given the class definitions:
public class Base{/*members*/}
public class Derived: Base {/*members*/}
The following code snipet is ok:
Base b = new Derived();
Derived d = (Derived)b;
However this snipet will raise an exception:
Base b = new Base();
Derived d = (Derived)b;
Hope this helps,
Sam