Prev | Current Page 291 | Next

Jon Skeet

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

I??™d usually write the last line
of listing 5.6 as something like
x.ForEach(delegate(int n)
{ Console.WriteLine(Math.Sqrt(n)); }
);
The parentheses and braces are now less confusing, and the ???what it does??? part stands
out appropriately. Of course, how you space out your code is entirely your own business,
but I encourage you to actively think about where you want to strike the balance,
and talk about it with your teammates to try to achieve some consistency. Consistency
doesn??™t always lead to the most readable code, however??”sometimes keeping everything
on one line is the most straightforward format.
You should also consider how much code it makes sense to include in anonymous
methods. The first two examples in listing 5.5 are reasonable , but printMean is probably
doing enough work to make it worth having as a separate method. Again, it??™s a balancing
act.
So far the only interaction we??™ve had with the calling code is through parameters.
What about return values?
5.4.2 Returning values from anonymous methods
The Action delegate has a void return type, so we haven??™t had to return anything
from our anonymous methods. To demonstrate how we can do so when we need to,
we??™ll use the new Predicate delegate type. We saw this briefly in chapter 3, but
here??™s its signature just as a reminder:
public delegate bool Predicate(T obj)
Listing 5.


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