Compartir a través de


Events (C# Programming Guide) 

An event is a way for a class to provide notifications when something of interest happens. For example, a class that encapsulates a user interface control might define an event to occur when the user clicks on the control. The control class does not care what happens when the button is clicked, but it does need to tell derived classes that the click event has occurred. The derived classes can then choose how to respond.

Events use delegates to provide type-safe encapsulation of the methods that will be called when triggered. A delegate can encapsulate both Named Methods and Anonymous Methods.

In the following example, the class TestButton contains the event OnClick. Classes that derive from TestButton can choose to respond to the OnClick event, and also define the methods that are to be called in order to handle the event. Multiple handlers, in the form of delegates and anonymous methods, can be specified.

// Declare the handler delegate for the event
public delegate void ButtonEventHandler();

class TestButton
{
    // OnClick is an event, implemented by a delegate ButtonEventHandler.
    public event ButtonEventHandler OnClick;

    // A method that triggers the event:
    public void Click()
    {
        OnClick();
    }
}
// Create an instance of the TestButton class.
TestButton mb = new TestButton();

// Specify the method that will be triggered by the OnClick event.
mb.OnClick += new ButtonEventHandler(TestHandler);

// Specify an additional anonymous method.
mb.OnClick += delegate { System.Console.WriteLine("Hello, World!"); };

// Trigger the event
mb.Click();

Events Overview

Events have the following properties:

  • An event is a way for a class to notify objects that they need to perform an action of some kind.

  • The most common use for events is in graphical user interfaces, although events can be useful at other times, such as signaling state changes.

  • Events are usually declared using delegate event handlers.

  • Events can call anonymous methods in place of delegates. For more information, see Anonymous Methods.

For more information, see:

C# Language Specification

For more information, see the following sections in the C# Language Specification:

  • 1.6.6.4 Events

  • 10.2.7.2 Member Names Reserved for Events

  • 10.7 Events

  • 13.2.3 Interface Events

See Also

Concepts

C# Programming Guide
Delegates (C# Programming Guide)

Other Resources

Creating Event Handlers in Windows Forms