?– Captured variables aren??™t really local variables??”extra types are created where
necessary.
?– Be careful! Simple is almost always better than clever.
We??™ll see more variables being captured when we look at C# 3 and its lambda expressions,
but for now you may be relieved to hear that we??™ve finished our rundown of the
new C# 2 delegate features.
160 CHAPTER 5 Fast-tracked delegates
5.6 Summary
C# 2 has radically changed the ways in which delegates can be created, and in doing
so it??™s opened up the framework to a more functional style of programming. There
are more methods in .NET 2.0 that take delegates as parameters than there were in
.NET 1.0/1.1, and this trend continues in .NET 3.5. The List
type is the best
example of this, and is a good test-bed for checking your skills at using anonymous
methods and captured variables. Programming in this way requires a slightly different
mind-set??”you must be able to take a step back and consider what the ultimate
aim is, and whether it??™s best expressed in the traditional C# manner, or whether a
functional approach makes things clearer.
All the changes to delegate handling are useful, but they do add complexity to the
language, particularly when it comes to captured variables. Closures are always tricky
in terms of quite how the available environment is shared, and C# is no different in
this respect.
Pages:
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326