Is it possible to promote an instance to an instance of a derived class?
For example, say there is a base class Vehicle
.
Vehicle
has derived classes: Boat
, Automobile
, Airplane
, etc...
When an new instance of type Vehicle
is created, the type of vehicle is unknown.
Later, it is discovered what the vehicle is, say it's a Boat
.
Is it possible to promote the Vehicle
instance to a Boat
object?
Clarification: the Vehicle
instance may have contents set and the promoted object needs to have those contents persist
P.S. I'm successfully doing this now, but by-hand and in a very clunky manner. So, I'm wondering if there is a generally accepted, canonical way.
(24-Sep-2017) Added real case per question by Eric Lippert below:
*My entire C# experience is self-taught, so I don't have an academic foundation and don't know much regarding "patterns" and so forth. The ideas of a factory pattern and composite patterns sound interesting and may be a better way to approach the problem (need to study up).
My real-world case is that I automate electronic measurements using measurement equipment (peripherals) that connect to the computer using a shared-bus architecture. On any given test bench, a variety of different peripherals might be connected at the user's option. To automatically figure out what peripherals are available, I execute a home-grown discovery process that finds the bus address of each connected peripheral. Then, to communicate with the discovered peripheral of unknown type I create an instance of a base class I call Device
. Device
has certain fundamental I/O protocol methods and properties such as bus address, communication timeout and so on. Using Device
I then query the peripheral for its identity to find out the manufacturer, model and serial number.
From that information I ascertain the type of peripheral and would like to "promote" the instance of Device
to an instance of a derived class specifically for that peripheral type, such as SpectrumAnalyzer
or Oscilloscope
or whatever.
I think what I've unwittingly done is create a sort cross between a factory class and a base class. Once the type of peripheral is known, Device
has a method that creates a new instance of a derived class and deeply copies its own properties to that derived instance.
Maybe if I re-think the solution in terms of factory pattern and not as a base class, I can improve the logic.
Interesting stuff... thanks for that.*