Prev | Current Page 275 | Next

Jon Skeet

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

The largest section of the chapter is devoted
to the most complicated part of anonymous methods, captured variables, which provide
delegate instances with a richer environment to play in. We??™ll cover the topic in
significant detail due to its importance and complexity.
First, though, let??™s remind ourselves of the pain points of C# 1??™s delegate facilities.
5.1 Saying goodbye to awkward delegate syntax
The syntax for delegates in C# 1 doesn??™t sound too bad??”the language already has syntactic
sugar around Delegate.Combine, Delegate.Remove, and the invocation of delegate
instances. It makes sense to specify the delegate type when creating a delegate
instance??”it??™s the same syntax used to create instances of other types, after all.
This is all true, but for some reason it also sucks. It??™s hard to say exactly why the delegate
creation expressions of C# 1 raise hackles, but they do??”at least for me. When
hooking up a bunch of event handlers, it just looks ugly to have to write ???new
EventHandler??? (or whatever is required) all over the place, when the event itself has
specified which delegate type it will use. Beauty is in the eye of the beholder, of course,
and you could argue that there??™s less call for guesswork when reading event handler wiring
code in the C# 1 style, but the extra text just gets in the way and distracts from the
important part of the code: which method you want to handle the event.


Pages:
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287