(Reflector knows
how to interpret the IL to display anonymous methods in the method that uses them,
but the extra methods are still visible.)
It??™s worth pointing out at this stage that listing 5.5 is ???exploded??? compared with
how you may well see anonymous methods in real code. You??™ll often see them used
as parameters to another method (rather than assigned to a variable of the delegate
type) and with very few line breaks??”compactness is part of the reason for
using them, after all. For example, we mentioned in chapter 3 that List
has a
ForEach method that takes an Action as a parameter and performs that action
on each element. Listing 5.6 shows an extreme example of this, applying the same
???square rooting??? action we used in listing 5.5, but in a compact form.
List x = new List();
x.Add(5);
x.Add(10);
x.Add(15);
x.Add(20);
x.Add(25);
x.ForEach(delegate(int n){Console.WriteLine(Math.Sqrt(n));});
That??™s pretty horrendous??”especially when at first sight the last six characters appear to
be ordered almost at random. There??™s a happy medium, of course. I tend to break my
4 One slight oddity is that if you??™re writing an anonymous method in a value type, you can??™t reference this from
within it. There??™s no such restriction within a reference type.
Listing 5.6 Extreme example of code compactness. Warning: unreadable code ahead!
Invokes delegates
as normal
D
Anonymous
methods
just contain
normal code
147 Inline delegate actions with anonymous methods
usual ???braces on a line on their own??? rule for anonymous methods (as I do for trivial
properties) but still allow a decent amount of whitespace.
Pages:
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302