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?
2 Answers
Know the answer? Post it. Somebody with the same question will find it here.
Sam112 pointsPosted Aug 8, 2007, 4:25 AM EDT
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
Keiron5 pointsPosted Aug 8, 2007, 4:53 AM EDT