Chapter 9. Delegates, Lambdas, and Events

The most common way to use an API is to invoke the methods and properties its classes provide, but sometimes, things need to work in reverse. In Chapter 5, I showed the search features offered by arrays and lists. To use these, I wrote a method that returned true when its argument met my criteria, and the relevant APIs called my method for each item they inspected. Not all callbacks are immediate. Asynchronous APIs can call a method in our code when long-running work completes. In a client-side application, I want my code to run when the user interacts with certain visual elements in particular ways, such as clicking a button.

Interfaces and virtual methods can enable callbacks. In Chapter 4, I showed the IComparer<T> interface, which defines a single CompareTo method. This is called by methods like Array.Sort when we want a customized sort ordering. You could imagine a UI framework that defined an IClickHandler interface with a Click method, and perhaps also DoubleClick. The framework could require us to implement this interface if we want to be notified of button clicks.

In fact, none of .NET’s UI frameworks use the interface-based approach, because it gets cumbersome when you need multiple kinds of callback. Single- and double-clicks are the tip of the iceberg for user interactions—in WPF applications, each user interface element can provide over 100 kinds of notifications. Most of the time, you need to handle only one or two events from ...

Get Programming C# 5.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.