Prev | Current Page 292 | Next

Jon Skeet

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

7 shows an anonymous method creating an instance of Predicate to
return whether the argument passed in is odd or even. Predicates are usually used in
filtering and matching??”you could use the code in listing 5.7 to filter a list to one containing
just the even elements, for instance.
Predicate isEven = delegate(int x)
{ return x%2 == 0; };
Console.WriteLine(isEven(1));
Console.WriteLine(isEven(4));
The new syntax is almost certainly what you??™d have expected??”we just return the
appropriate value as if the anonymous method were a normal method. You may have
expected to see a return type declared near the parameter type, but there??™s no need.
The compiler just checks that all the possible return values are compatible with the
declared return type of the delegate type it??™s trying to convert the anonymous
method into.
Listing 5.7 Returning a value from an anonymous method
148 CHAPTER 5 Fast-tracked delegates
NOTE Just what are you returning from? When you return a value from an anonymous
method it really is only returning from the anonymous method??”
it??™s not returning from the method that is creating the delegate instance.
It??™s all too easy to look down some code, see the return keyword, and
think that it??™s an exit point from the current method.
Relatively few delegates in .NET 2.0 return values??”in particular, few event handlers
do, partly because when the event is raised only the return value from the last action
to be called would be available.


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