#380 – Handling Events that Use the EventHandler Delegate Type
August 2, 2011 Leave a comment
Events that return no event data should normally use the built-in EventHandler delegate type.
public event EventHandler Barked;
EventHandler is a delegate that takes two parameters.
public delegate void EventHandler(object o, EventArgs e);
The first parameter is assumed to be a reference to the object that raised the event. The second parameter will contain a reference to some subclass of the EventArgs class, if the event does return data, or will be a null value, if the event does not pass data back.
Here’s an example of subscribing to the Barked event defined above.
// Subscribing to the event Dog kirby = new Dog("Kirby"); kirby.Barked += kirby_Barked; kirby.Bark();
And an example of a handler for the Barked event.
static void kirby_Barked(object o, EventArgs e) { Console.WriteLine("Kirby barked"); }