
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
486
Chapter 9
CHAPTER 9
Delegates, Events,
and Anonymous Methods
9.0 Introduction
Delegates contain all that is needed to allow a method, with a specific signature and
return type, to be invoked by your code. A delegate can be passed to methods and a
reference to it can be stored in a structure or class. A delegate is used when, at design
time, you do not know which method you need to call and the information to deter-
mine this is available only at runtime.
Another scenario is when the code calling a method is being developed indepen-
dently of the code that will supply the method to be called. The classic example is a
Windows Forms control. If you create a control, you are unlikely to know what
method should be called in the application when the control raises an event, so you
must provide a delegate to allow the application to hook up a handler to the event.
When other developers use your control, they will typically decide when they are
adding the control (through the designer or programmatically) and which method
should be called to handle the event published by the control. (For example, it’s
common to connect a
Button’s click handler to a delegate at design time.)
Anonymous methods are delegates without the full delegate syntax. They are a fea-
ture of the C# compiler and not a CLR ...