I am wondering why this populates the derived class appropriately:
BaseClass bc = MethodThatReturnsBaseClassObject();
DerivedClass dc = bc as DerivedClass;
But this creates a null derived class object:
DerivedClass dc = MethodThatReturnsBaseClassObject() as DerivedClass;
This happens because BaseClass
is not an instance of DerivedClass
(but DerivedClass
is an instance of BaseClass
), so you cannot cast an instance of the base class as an instance of the derived class (well, you can, but it will be null as you have found).
You can do what (I think) you are trying to achieve by adding a constructor to the derived class that takes in the base class as a parameter:
public DerivedClass(BaseClass baseClass) {
// Populate common properties, call other derived class constructor, or call base constructor
}
Then:
DerivedClass dc = new DerivedClass(MethodThatReturnsBaseClassObject());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With