Declare a delegate type to create an abstraction of a method signature.
Create an instance of a delegate to refer to a specific method and to an anonymous method.
Call a method through a delegate.
Declare an event field.
Handle an event by using a delegate.
Raise an event.
Much of the code you have written in the various exercises in this book has assumed that statements execute sequentially. While this is a common scenario, you will find that it is sometimes necessary to interrupt the current flow of execution and perform another more important task. When the task has completed, the program can continue where it left off. The classic example of this style of program is the Windows Form. A form displays controls such as buttons and text boxes. When you click a button or type text in a text box, you expect the form to respond immediately. The application has to temporarily stop what it is doing, and go and handle your input. This style of operation applies not just to graphical user interfaces, but to any application where an operation must be performed urgently—shutting down the reactor in a nuclear power plant if it is getting too hot, for example.
In order to handle this type of application, the runtime has to provide two things: a means of indicating that something urgent has happened, and a way of indicating a method that should be run when it happens. This is the purpose of events and delegates. We will start by looking at delegates.