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.
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
.
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