Enabling Notifications with Events
In the previous section, you saw how to declare a delegate type, call a delegate, and create delegate instances. However, this is only half the story. Although delegates allow you to invoke any number of methods indirectly, you still have to invoke the delegate explicitly. In many cases, it would be useful to have the delegate run automatically when something significant happens. For example, in the automated factory scenario, it could be vital to be able to invoke the stopMachinery delegate and halt the equipment if a machine overheats. In the .NET Framework, events allow you to define and trap significant actions, and arrange for a delegate to be called to handle the situation. Many classes in the .NET Framework expose events. Most of the controls that you can place on a Windows form, and the Windows Form class itself, use events to allow you to run code when, for example, the user clicks a button or types something in to a field. You can also define your own events.