Chapter 7. Delegates and Events
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 used
similarly to an object; for example, it can be passed to methods and
stored in a data structure. A delegate is used when, at design time,
you do not know which method you need to call and the information to
determine this is available only at runtime.
Another scenario is when the code calling a method is being developed
independently of the code that will supply the method to be called.
The classic example is a Windows Forms control. If you design a
control, you are unlikely to know what method should be called when
the application raises an event, so you must use a delegate. However,
when others use your control, they will typically decide at design
time which method to call. (For example, it's common
to connect a Button's click
handler to a delegate at design time.)
This chapter's recipes make use of delegates and
events. These recipes cover handling each method invoked in a
multicast delegate individually, synchronous delegate invocation
versus asynchronous delegate invocation, and enhancing an existing
class with events, among other topics. If you are not familiar with
delegates and events, you should read the MSDN documentation on these
topics. There are also good tutorials and example code showing you
how to set up and use delegates and events.
|