Search code examples
c#eventsderived-classbase-class

Event handler inheritance


I have a parent class that is firing an event to derived classes. The problem is that the event handler is alway null.

Class Plugin()
{
    public delegate void BufferReadyHandler(string str);
    public event BufferReadyHandler OnBufferReady;
    public ClassPlugin(eGuiType _guyType)
    {
        GuiType = _guyType;
    }
    protected void Sp_DataReceived_Parent(object sender, SerialDataReceivedEventArgs e)
    {
        strCommonBuffer += serial.ReadExisting();
        if (strCommonBuffer.Contains("\r\n"))
        {
            if (OnBufferReady != null) <<-------NULL
                OnBufferReady(strCommonBuffer);
            strCommonBuffer = string.Empty;
        }
    }
}

then there are some derived classes that are linked to that event:

class ClassIO : ClassPlugin
{
    public ClassIO(eGuiType _guyType) : base(_guyType)
    {
        ...
        OnBufferReady += ClassIO_OnBufferReady;
    }

    private void ClassIO_OnBufferReady(string str)
    {
        ...
    }
}

the problem is that the OnBufferReady event in the parent class is alway null and therefore never fired. Thanks for any help.


Solution

  • I might be wrong but have you thought about making the event static?

    public delegate void BufferReadyHandler(string str);
    public static event BufferReadyHandler OnBufferReady;