Prev | Current Page 276 | Next

Jon Skeet

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


Life becomes a bit more black and white when you consider covariance and contravariance
as applied to delegates. Suppose you??™ve got an event handling method
that saves the current document, or just logs that it??™s been called, or any number of
other actions that may well not need to know details of the event. The event itself
shouldn??™t mind that your method is capable of working with only the information provided
by the EventHandler signature, even though it is declared to pass in mouse
event details. Unfortunately, in C# 1 you have to have a different method for each different
event handler signature.
139 Saying goodbye to awkward delegate syntax
Likewise it??™s undeniably ugly to write methods that are so simple that their implementation
is shorter than their signature, solely because delegates need to have code
to execute and that code has to be in the form of a method. It adds an extra layer of
indirection between the code creating the delegate instance and the code that should
execute when the delegate instance is invoked. Often extra layers of indirection are
welcome??”and of course that option hasn??™t been removed in C# 2??”but at the same
time it often makes the code harder to read, and pollutes the class with a bunch of
methods that are only used for delegates.
Unsurprisingly, all of these are improved greatly in C# 2. The syntax can still occasionally
be wordier than we might like (which is where lambda expressions come into
play in C# 3), but the difference is significant.


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