Compartir a través de


How to: Implement Two Interfaces that Have an Event with the Same Name (C# Programming Guide) 

Another use for event properties covers the situation where you are implementing two interfaces, each with an event of the same name. In such a case, you must use an explicit implementation event property.

However, when explicitly implementing events in interface, you need to provide add and remove methods.

Example

public delegate void Delegate1();
public delegate int Delegate2(string s);

public interface I1
{
    event Delegate1 TestEvent;
}

public interface I2
{
    event Delegate2 TestEvent;
}

public class ExplicitEventsSample : I1, I2
{
    public event Delegate1 TestEvent;     // normal implementation of I1.TestEvent.
    private Delegate2 TestEvent2Storage;  // underlying storage for I2.TestEvent.

    event Delegate2 I2.TestEvent   // explicit implementation of I2.TestEvent.
    {
        add
        {
            TestEvent2Storage += value;
        }
        remove
        {
            TestEvent2Storage -= value;
        }
    }

    private void FireEvents()
    {
        if (TestEvent != null)
        {
            TestEvent();
        }
        if (TestEvent2Storage != null)
        {
            TestEvent2Storage("hello");
        }
    }
}

See Also

Reference

Interfaces (C# Programming Guide)
Explicit Interface Implementation (C# Programming Guide)

Concepts

C# Programming Guide
Events (C# Programming Guide)
Delegates (C# Programming Guide)