Prev | Current Page 295 | Next

Jon Skeet

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

MouseClick += delegate { Console.WriteLine("LogMouse"); };
Form form = new Form();
form.AutoSize=true;
form.Controls.Add(button);
Application.Run(form);
Normally we??™d have had to write each subscription as something like this:
button.Click += delegate (object sender, EventArgs e) { ... };
That wastes a lot of space for little reason??”we don??™t need the values of the parameters,
so the compiler lets us get away with not specifying them at all. Listing 5.9 also
happens to be a perfect example of how consistency of formatting isn??™t always a good
thing??”I played around with a few ways of laying out the code and decided this was the
clearest form.
I??™ve found this shortcut most useful when it comes to implementing my
own events. I get sick of having to perform a nullity check before raising
an event. One way of getting around this is to make sure that the
event starts off with a handler, which is then never removed. As long as
the handler doesn??™t do anything, all you lose is a tiny bit of performance.
Before C# 2, you had to explicitly create a method with the
right signature, which usually wasn??™t worth the benefit. Now, however,
you can do this:
public event EventHandler Click = delegate {};
From then on, you can just call Click without any tests to see whether there are any
handlers subscribed to the event.
You should be aware of one trap about this ???parameter wildcarding??? feature??”if
the anonymous method could be converted to multiple delegate types (for example,
Listing 5.


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