Partager via


How to: Declare an Event in an Interface and Implement it in a Class (C# Programming Guide) 

This example shows that it is possible to declare an event in an interface and implement it in a class.

Example

public delegate void TestDelegate();   // delegate declaration

public interface ITestInterface
{
    event TestDelegate TestEvent;
    void FireAway();
}

public class TestClass : ITestInterface
{
    public event TestDelegate TestEvent;

    public void FireAway()
    {
        if (TestEvent != null)
        {
            TestEvent();
        }
    }
}

public class MainClass
{
    static private void F()
    {
        System.Console.WriteLine("This is called when the event fires.");
    }

    static void Main()
    {
        ITestInterface i = new TestClass();

        i.TestEvent += new TestDelegate(F);
        i.FireAway();
    }
}

See Also

Concepts

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