Chapter 9. Delegating Those Important Events
In This Chapter
Using delegates to solve the callback problem
Using delegates to customize a method
Implementing delegates by using anonymous methods
Using C# events to notify the world when interesting events happen
This chapter looks into a corner of C# that has been around since the birth of the language, but one that I've avoided because it's challenging stuff. However, if you can bear with me — and I try to go as easy on you as possible — the payoff is well worth it.
E.T., Phone Home — The Callback Problem
If you've seen the Steven Spielberg movie E.T., the Extraterrestrial (1982), you watched the cute but ugly little alien stranded on Earth try to build an apparatus from old toy parts with which he could "phone home." He needed his ship to pick him up.
It's a big jump from E.T. to C#, but code sometimes needs to phone home, too. For example, you may have wondered how the Windows progress bar works. It's the horizontal "bar" that gradually fills up with coloring to show progress during a lengthy operation, such as copying files. (On my machine, of course, good old Murphy's law — "Whatever can go wrong will go wrong" — seems to fill it up well before the task is finished. Figure 9-1 shows a green progress bar (though it isn't easy being green in a black-and-white book).
The progress bar is based on a lengthy operation's periodic pause to "phone home." In programmerese, it's a callback. Usually, the lengthy operation estimates how long its ...
Get C# 2010 All-in-One For Dummies® 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.