Listing 5.1 Subscribing to three of a button's events
140 CHAPTER 5 Fast-tracked delegates
5.2 Method group conversions
In C# 1, if you want to create a delegate instance you need to specify both the delegate
type and the action. If you remember from chapter 2, we defined the action to be the
method to call and (for instance methods) the target to call it on. So for example, in listing
5.1 when we needed to create a KeyPressEventHandler we used this expression:
new KeyPressEventHandler(LogKeyEvent)
As a stand-alone expression, it doesn??™t look too bad. Even used in a simple event subscription
it??™s tolerable. It becomes a bit uglier when used as part of a longer expression.
A common example of this is starting a new thread:
Thread t = new Thread (new ThreadStart(MyMethod));
What we want to do is start a new thread that will execute MyMethod as simply as possible.
C# 2 allows you to do this by means of an implicit conversion from a method group
to a compatible delegate type. A method group is simply the name of a method,
optionally with a target??”exactly the same kind of expression as we used in C# 1 to create
delegate instances, in other words. (Indeed, the expression was called a method
group back then??”it??™s just that the conversion wasn??™t available.) If the method is
generic, the method group may also specify type arguments. The new implicit conversion
allows us to turn our event subscription into
button.
Pages:
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290