Chapter 19. Delegates and EventsWhen a head of state dies, the president of the United States typically does not have time to attend the funeral personally. Instead, he dispatches a delegate. Often this delegate is the vice president, but sometimes the VP is unavailable and the president must send someone else, such as the secretary of state or even the first lady. He does not want to "hardwire" his delegated authority to a single person; he might delegate this responsibility to anyone who is able to execute the correct international protocol. The president defines in advance what authority will be delegated (attend the funeral), what parameters will be passed (condolences, kind words), and what value he hopes to get back (good will). He then assigns a particular person to that delegated responsibility at "runtime," as the course of his presidency progresses. In programming, you are often faced with situations where you need to execute a particular action, but you don't know in advance which method you'll want to call to execute that action. You might not even know which object you'll perform the action with. For example, a button might know that it must notify some object when it is pushed, but it might not know which object or objects need to be notified. Rather than wiring the button to a particular object, you will connect the button to a delegate and then resolve that delegate to a particular method when the program executes. Today's Graphical User Interface (GUI) programming model requires event-driven programming. A GUI program waits for the user to take an action, such as choosing among menu selections, pushing buttons, updating text fields, and clicking icons. Each action causes an event to be raised. Other events can be raised without direct user action, such as events that correspond to timer ticks of the internal clock, email being received, and file-copy operations completing. An event is the encapsulation of the idea that "something happened," to which the program must respond. Events and delegates are tightly coupled concepts because flexible event handling requires that the response to the event be dispatched to the appropriate event handler. An event handler is typically implemented in C# as a delegate. |