"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to correctly trigger inherited events in derived classes in C#

How to correctly trigger inherited events in derived classes in C#

Posted on 2025-04-14
Browse:271

How Can I Properly Raise Inherited Events in C# Derived Classes?

Raising Events Inherited from a Base Class in C#

In C#, it is common practice to inherit events from a base class to facilitate event handling in derived classes. However, raising such inherited events requires a specific approach to avoid compiler errors.

Consider a scenario where a base class defines the following events:

public class BaseClass
{
    public event EventHandler Loading;
    public event EventHandler Finished;
}

In a derived class, attempting to raise the Loading event using:

this.Loading(this, new EventHandler());

results in the error:

The event 'BaseClass.Loading' can only appear on the left hand side of  = or -= (BaseClass')

This error occurs because events, unlike other class members, cannot be invoked directly by the derived class. Instead, inherited events must be raised by invoking specific methods defined in the base class. To achieve this, the following steps are necessary:

  1. Create Protected Event-Raising Methods in the Base Class:
    Define protected methods in the base class that are responsible for raising the events. For example:
public class BaseClass
{
    public event EventHandler Loading;
    public event EventHandler Finished;

    protected virtual void OnLoading(EventArgs e)
    {
        EventHandler handler = Loading;
        if( handler != null )
        {
            handler(this, e);
        }
    }

    protected virtual void OnFinished(EventArgs e)
    {
        EventHandler handler = Finished;
        if( handler != null )
        {
            handler(this, e);
        }
    }
}
  1. Invoke Event-Raising Methods in Derived Classes:
    In derived classes, instead of directly invoking the events, call the corresponding event-raising methods defined in the base class. For instance:
public class DerivedClass : BaseClass
{
    public void DoSomething()
    {
        // Raise Loading event
        OnLoading(EventArgs.Empty);

        // Raise Finished event
        OnFinished(EventArgs.Empty);
    }
}

By following this approach, inherited events can be safely and efficiently raised in derived classes in C#.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3