Prev | Current Page 300 | Next

Jon Skeet

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

It behaves exactly the way that local variables
always have.
?–  anonLocal e isn??™t an outer variable either, but it??™s local to the anonymous
method, not to EnclosingMethod. It will only exist (in terms of being present in
an executing stack frame) when the delegate instance is invoked.
?–  outerVariable B is an outer variable because the anonymous method is
declared within its scope. However, the anonymous method doesn??™t refer to it,
so it??™s not captured.
?–  capturedVariable c is an outer variable because the anonymous method is
declared within its scope, and it??™s captured by virtue of being used at f.
Okay, so we now understand the terminology, but we??™re not a lot closer to seeing
what captured variables do. I suspect you could guess the output if we ran the
method from listing 5.10, but there are some other cases that would probably surprise
you. We??™ll start off with a simple example and gradually build up to more complex
ones.
5.5.2 Examining the behavior of captured variables
When a variable is captured, it really is the variable that??™s captured by the anonymous
method, not its value at the time the delegate instance was created. We??™ll see later that
this has far-reaching consequences, but first we??™ll make sure we understand what that
means for a relatively straightforward situation. Listing 5.11 has a captured variable
and an anonymous method that both prints out and changes the variable.


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