C#: Raising an inherited event

jwarzech picture jwarzech · Apr 16, 2009 · Viewed 63.4k times · Source

I have a base class that contains the following events:

public event EventHandler Loading;
public event EventHandler Finished;

In a class that inherits from this base class I try to raise the event:

this.Loading(this, new EventHandler()); // All we care about is which object is loading.

I receive the following error:

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

I am assuming I cannot access these events the same as other inherited members?

Answer

Frederik Gheysels picture Frederik Gheysels · Apr 16, 2009

What you have to do , is this:

In your base class (where you have declared the events), create protected methods which can be used to raise the events:

public class MyClass
{
   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);
       }
   }
}

(Note that you should probably change those methods, in order to check whether you have to Invoke the eventhandler or not).

Then, in classes that inherit from this base class, you can just call the OnFinished or OnLoading methods to raise the events:

public AnotherClass : MyClass
{
    public void DoSomeStuff()
    {
        ...
        OnLoading(EventArgs.Empty);
        ...
        OnFinished(EventArgs.Empty);
    }
}