The covariance and contravariance features we??™ve just talked about can
sometimes help with the first problem, but often they don??™t. Anonymous methods, which
are also new in C# 2, can pretty much always help with these issues.
Informally, anonymous methods allow you to specify the action for a delegate
instance inline as part of the delegate instance creation expression. This means there??™s
Listing 5.4 Demonstration of breaking change between C# 1 and C# 2
3 In case you skipped the first chapter, Snippy is a tool I??™ve used to create short but complete code samples. See
section 1.4.2 for more details.
145 Inline delegate actions with anonymous methods
no need to ???pollute??? the rest of your class with an extra method containing a small
piece of code that is only useful in one place and doesn??™t make sense elsewhere.
Anonymous methods also provide some far more powerful behavior in the form
of closures, but we??™ll come to them in section 5.5. For the moment, let??™s stick with relatively
simple stuff??”as you may have noticed, a common theme in this book is that
you can go a long way in C# 2 without dealing with the more complex aspects of the
language. Not only is this good in terms of learning the new features gradually, but
if you only use the more complicated areas when they provide a lot of benefit, your
code will be easier to understand as well.
Pages:
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299