Events

Graphical User Interfaces (GUIs) require that programs respond to events. An event might be a button push, a menu selection, the completion of a file transfer, or a similar occurrence. In a GUI environment, any number of widgets can raise an event. For example, when you click a Button, it might raise the Click event. When you add to a drop-down list, it might raise a ListChanged event.

Whenever something happens in relation to the program (whenever an event is raised), the code must provide a way to respond to it. You cannot predict the order in which events will arise. The system is quiescent until the event, and then it springs into action to handle the event.

Other classes will be interested in responding to these events. How they respond is not of interest to the class raising the event. The button says “I was clicked,” and the responding classes react appropriately.

Publishing and Subscribing

In C#, any object can publish a set of events to which other classes can subscribe. When the publishing class raises an event, all the subscribed classes are notified.

Tip

This design implements the publish/subscribe (also know as the observer) pattern described in the seminal work Design Patterns by Gamma et al. (Addison Wesley). Gamma et al. describe the intent of this pattern: “Define a one to many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.”

With this mechanism, your object can say “Here are ...

Get Learning C# now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.