BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 1.1+

C# Interface Events

An interface can be created to define a contract containing members that classes that implement it must provide. Interfaces can define events, sometimes leading to classes that implement several interfaces being required to declare an event name twice.

Implementing Two Interfaces with a Single Event

In some cases the two interface events with matching names will be logically linked. This may mean that whenever one is raised, the other should be also. Rather than defining the two events entirely separately, it is useful to declare a single delegate to be used by both.

This is demonstrated in the final sample below. Here the Test class has been updated to remove one of the delegates and one method that was used to raise an event. Both events now add and remove subscribers using the same delegate.

public class Test : INotify, INotifier
{
    EventHandler _notify;
    object _lock = new object();

    event EventHandler INotify.Notify
    {
        add
        {
            lock (_lock)
            {
                _notify += value;
            }
        }
        remove
            {
            lock (_lock)
            {
                _notify -= value;
            }
        }
    }

    public void NotifyNow()
    {
        OnNotify(new EventArgs());
    }

    void OnNotify(EventArgs e)
    {
        if (_notify != null) _notify(this, e);
    }

    event EventHandler INotifier.Notify
    {
        add
        {
            lock (_lock)
            {
                _notify += value;
            }
        }
        remove
        {
            lock (_lock)
            {
                _notify -= value;
            }
        }
    }

    public void RaiseEvent()
    {
        OnNotify(new EventArgs());
    }
}

To see the updated class in action, re-run the program. You will now see that when the NotifyNow method is called, both event subscribers are executed, outputting two messages. When the RaiseEvent method is called, both event subscribers are run for a second time, generating four messages in total.

24 September 2010