CramerTV CramerTV - 2 months ago 7
C# Question

How do I call a derived class method from the base class?

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?

Answer

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:

public class WireLessDevice
{ // base class
    protected virtual void ParseMessage()
    {
        // Do common stuff in here
    }
}

public class WiFi : WireLessDevice
{ // derived class
    override void ParseMessage()
    {
        base.ParseMessage();//Call this if you need some operations from base impl.
        DoGPSStuff();
    }
    private void DoGPSStuff()
    {
        //some gps stuff
    }
    GPSLoc Loc;
}
Comments