Prev | Current Page 298 | Next

Jon Skeet

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


151 Capturing variables in anonymous methods
Stick with it, though! The payback can be massive in terms of code simplicity and
readability. This topic will also be crucial when we come to look at lambda expressions
and LINQ in C# 3, so it??™s worth the investment. Let??™s start off with a few definitions.
5.5.1 Defining closures and different types of variables
The concept of closures is a very old one, first implemented in Scheme, but it??™s been gaining
more prominence in recent years as more mainstream languages have taken it on
board. The basic idea is that a function5 is able to interact with an environment beyond
the parameters provided to it. That??™s all there is to it in abstract terms, but to understand
how it applies to C# 2, we need a couple more terms:
?–  An outer variable is a local variable or parameter6 whose scope includes an anonymous
method. The this reference also counts as an outer variable of any
anonymous method where it can be used.
?–  A captured outer variable (usually shortened to just ???captured variable???) is an outer
variable that is used within an anonymous method. So to go back to closures,
the function part is the anonymous method, and the environment it can interact
with is the set of variables captured by it.
That??™s all very dry and may be hard to imagine, but the main thrust is that an anonymous
method can use local variables defined in the same method that declares it.


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