Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a base class to a derived class

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;
like image 436
user2023116 Avatar asked Nov 05 '13 23:11

user2023116


1 Answers

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());
like image 80
mayabelle Avatar answered Sep 18 '22 22:09

mayabelle