I have read several similar questions about this but none seem to solve the problem I am facing. The typical answer is to cast as the derived class but I cannot since I do not know the derived class type.
Here is my example:
class WireLessDevice { // base class
void websocket.parsemessage(); // inserts data into the wireless device object
}
class WiFi : WireLessDevice { // derived class
GPSLoc Loc;
}
Wireless Device can also be derived to make Bluetooth, Wi-Max, Cellular, etc. devices and thus I do not know which type of wirelessdevice will be receiving the data.
When a GPS packet is received on the websocket in the base class I need to update the derived device's location.
I thought perhaps sending a message via a queue or creating an event handler and sending the location in the event arguments but those seem a little clunky when the data is staying within the class.
Is there something built into the language that would allow me to call my derived device from the base class without knowing the type?
The correct way is to add a method DoSomeMagic() in the base class, with default implementation, or abstract. The derived class should than override it to do its magic.
Something like this maybe:
Virtual methods would be a good solution. You create a method
ParseMessage
in the base class which handles all the stuff common to each derived type, then override for specific devices.In order to still be able to handle other message types, you will need to call the
base.ParseMessage
as appropriate:If your base class is not handling any other messages, the code could be simpler (and using
abstract
). However, in that case I would consider moving the web socket code to the derived class.