Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Permanent casting to a superclass

If:

class Car : Automobile
{}

I can do:

Car toyota = new Car();
Automobile tauto = (Automobile)toyota;

but if I do tauto.GetType().Name it will still be Car.

Is it possible to perform a cast, so that the type is permanently changed to Automobile (without having to clone the object) ?

The problem i am trying to overcome is that there is no multiple inheritance in c#, and i need to merge objects (with the same signature) from 2 services, in one method, and return one type.

like image 424
Sonic Soul Avatar asked Oct 29 '10 15:10

Sonic Soul


1 Answers

No. There is no way to do this without constructing a new Automobile object.

However, there is also no reason to do this. The Liskov substitution principle says that any Car should, always, be treatable exactly like an Automobile, and the user should have no change in expected behavior.

As long as you design your class hierarchy correctly, using Car as an Automobile should always be perfectly acceptable.


On a side note: This is part of why using Type.GetType() is not the preferred way to check for type. It's much safer, and better, to use the is and as keywords in C#. They will return true if you check that tauto is Car.

like image 88
Reed Copsey Avatar answered Oct 09 '22 17:10

Reed Copsey