C# – Events and Interfaces

ceventsinterface

I have an interface with several events
I have base class implementing the interface
I have third class extending the base class (let's call it theConcreteClass)

problem: when i do something like: IMyInterface i = new theConcreteClass() and then i subscribe to any of the events (i.someEvent+=some_handler😉 the event handlers never invoked because (probably) the event subscription was assigned to the base class and not to the concrete class even though the new() operator created the concrete class.

hope it was clear 🙂
any suggestions?

thanks,
Adi Barda

Best Answer

What you are describing should work as expected.

Have you declared the events again in the concrete class hiding the base implementations?

Your code should be:

public interface IInterface
{
    event EventHandler TestEvent;
}

public class Base : IInterface
{
    public event EventHandler TestEvent;
}

public class Concrete : Base
{
   //Nothing needed here
}

To answer your comment:

Standard practice is to place a method on the base class:

public class Base : IInterface
{
    public event EventHandler TestEvent;

    protected virtual void OnTestEvent()
    {
        if (TestEvent != null)
       {
           TextEvent(this, EventArgs.Empty);
       }
    }
}

public class Concrete : Base
{
   public void SomethingHappened()
   {
       OnTestEvent();
   }
}

This pattern helps centralise any logic for firing the event, testing for null etc, and makes it easy to hook into the time that the event fires in child classes by overriding the method.