Prev | Current Page 294 | Next

Jon Skeet

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

(Sometimes you??™ll be calling Sort directly
at the point where the anonymous method is called for. In this case we??™re performing
the same fetch/sort/display sequence twice, just with different sort orders, so I encapsulated
that sequence in its own method.)
Listing 5.8 Using anonymous methods to sort files simply
149 Inline delegate actions with anonymous methods
There??™s one special syntactic shortcut that is sometimes available. If you don??™t care
about the parameters of a delegate, you don??™t have to declare them at all. Let??™s see
how that works.
5.4.3 Ignoring delegate parameters
Just occasionally, you want to implement a delegate that doesn??™t depend on its parameter
values. You may wish to write an event handler whose behavior was only appropriate
for one event and didn??™t depend on the event arguments: saving the user??™s
work, for instance. Indeed, the event handlers from our original example in listing
5.1 fit this criterion perfectly. In this case, you can leave out the parameter list
entirely, just using the delegate keyword and then the block of code to use as the
action for the method. Listing 5.9 is equivalent to listing 5.1 but uses this syntax.
Button button = new Button();
button.Text = "Click me";
button.Click += delegate { Console.WriteLine("LogPlain"); };
button.KeyPress += delegate { Console.WriteLine("LogKey"); };
button.


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