Prev | Current Page 289 | Next

Jon Skeet

"C# in Depth: What you need to master C# 2 and 3"

5 Anonymous methods used with the Action delegate type
B Uses anonymous
method to create
Action
C Uses loop in
anonymous
method
146 CHAPTER 5 Fast-tracked delegates
printReverse("Hello world");
printRoot(2);
printMean(samples);
Listing 5.5 shows a few of the different features of anonymous methods.
First, the syntax of anonymous methods: use the delegate keyword, followed
by the parameters (if there are any), followed by the code for the
action of the delegate instance, in a block. The string reversal code B
shows that the block can contain local variable declarations, and the ???list
averaging??? code C demonstrates looping within the block. Basically, anything
you can do in a normal method body, you can do in an anonymous
method.4 Likewise, the result of an anonymous method is a delegate
instance that can be used like any other one D. Be warned that contravariance
doesn??™t apply to anonymous methods: you have to specify the parameter types that
match the delegate type exactly.
In terms of implementation, we are still creating a method for each delegate
instance: the compiler will generate a method within the class and use that as the
action it uses to create the delegate instance, just as if it were a normal method. The
CLR neither knows nor cares that an anonymous method was used. You can see the
extra methods within the compiled code using ildasm or Reflector.


Pages:
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301