Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting from Base To Derived?

Tags:

c#

casting

Is it possible to cast an object from a base to a derived one? For instance, let's say I have one base object: Animal. From this I have derived a couple of other classes: Cat, Dog. Now I need an Animal but the type at this moment doesn't really matter. So,

Animal blankCanvas = new Animal();

Along the way I changed my mind and now want to change that Animal to a Dog. However, I don't understand how I would go about doing that. I know the business rules to convert from an Animal to a Dog but I just don't know how to implement that.

like image 827
Adam Beck Avatar asked Feb 19 '26 05:02

Adam Beck


1 Answers

Yes, you can cast a base reference to a derived reference.

But you seem to want to convert an instance. That is not casting and it is not directly possible.

Your logic should be such that you know what type you want at the point when you create it.

The following could make sense:

Animal blankCanvas = null;
...
blankCanvas = new Dog();

To help you to keep the correct path, define Animal as an abstract class
After all, what does an instance of Animal represent?

like image 53
Henk Holterman Avatar answered Feb 20 '26 17:02

Henk Holterman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!