O'Reilly logo

Programming C# 4.0 by Jesse Liberty, Matthew Adams, Ian Griffiths

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Notifying Clients with Events

An event is raised (or sent) by a publisher (or sender) when something of interest occurs (such as an action taking place, or a property changing). Clients can subscribe to the event by providing a suitable delegate, rather like the callbacks we used previously. The method wrapped by the delegate is called the event handler. The neat thing is that more than one client can subscribe to the event.

Here’s an example of a couple of events that we can add to the DocumentProcessor to help our production team:

class DocumentProcessor
{
    public event EventHandler Processing;
    public event EventHandler Processed;

    // ...
}

Notice that we use the keyword event to indicate that what follows is an event declaration. We then specify the delegate type for the event (EventHandler) and the name of the event (using PascalCasing). So, this is just like a declaration for a public field of type EventHandler, but annotated with the event keyword.

What does this EventHandler delegate look like? The framework defines it like this:

delegate void EventHandler(object sender, EventArgs e);

Notice that our delegate takes two parameters. The first is a reference to the publisher of the event so that subscribers can tell who raised it. The second is some data associated with the event. The EventArgs class is defined in the framework, and is a placeholder for events that don’t need any extra information. We’ll see how to customize this later.

Note

Almost all events follow this two-argument ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required