Events permit a class to declare notifications for which clients can attach executable code in the form of event handlers. Events are an important aspect of the design of class libraries in general, and of the system-provided class library in particular. C# provides an integrated solution for events.
A class defines an event by providing an event declaration, which looks quite similar to a field or event declaration but with an added event
keyword. The type of this declaration must be a delegate type. In the example below, the Button
class defines a Click
event of type EventHandler
.
public delegate void EventHandler(object sender, Event e); public class Button: Control { public event EventHandler Click; public void Reset() { Click = null; } }
Inside the Button
class, the Click
member can be corresponds exactly to a private field of type EventHandler
. However, outside the Button
class, the Click
member can only be used on the left hand side of the +=
and -=
operators. This restricts client code to adding or removing an event handler. In the client code example below, the Form1
class adds Button1_Click
as an event handler for Button1
’s Click
event. In the Disconnect
method, the event handler is removed.
using System; public class Form1: Form { public Form1() { // Add Button1_Click as an event handler for Button1’s Click event Button1.Click += new EventHandler(Button1_Click); } Button Button1 = new Button(); void Button1_Click(object sender, Event e) { Console.WriteLine("Button1 was clicked!"); } public void Disconnect() { Button1.Click -= new EventHandler(Button1_Click); } }
The Button
class could be rewritten to use a property-like event declaration rather than a field-like event declaration. This change has no effect on client code.
public class Button: Control { public event EventHandler Click { get {...} set {...} } public void Reset() { Click = null; } }