Chapter 17. Delegates and Events

When a head of state dies, the president of the United States sometimes 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 responsibility will be delegated (attend the funeral), what items 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, or even which object, you’ll want to call upon to execute it. For example, you might want to tell an object to play a media file during runtime, but you might not know what object will be playing the file, or whether it’s a video, a sound file, an animation, or something else. Rather than hardcoding a particular media player object, you would create a delegate, and then resolve that delegate to a particular method when the program executes.

In the early, dark, and primitive days of computing, ...

Get Learning C# 3.0 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.