Prev | Current Page 308 | Next

Jon Skeet

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

So, when we go
through and invoke each delegate D, we see the different values initially assigned to
counter: 0, 10, 20, 30, 40. Just to hammer the point home, when we then go back to
the first delegate instance and execute it three more times E, it keeps going from
where that instance??™s counter variable had left off: 1, 2, 3. Finally we execute the second
delegate instance F, and that keeps going from where that instance??™s counter
variable had left off: 11.
Listing 5.13 Capturing multiple variable instantiations with multiple delegates
Variable
instance is
captured
Instantiates counter B
Prints and increments
captured variable
C
D Executes all
five delegate
instances
Executes first one
three more times
E
Executes second one again F
157 Capturing variables in anonymous methods
So, each of the delegate instances has captured a different variable in this
case. Before we leave this example, I should point out what would have happened
if we??™d captured index??”the variable declared by the for loop??”
instead of counter. In this case, all the delegates would have shared the
same variable. The output would have been the numbers 5 to 14; 5 first
because the last assignment to index before the loop terminates would
have set it to 5, and then incrementing the same variable regardless of
which delegate was involved. We??™d see the same behavior with a foreach
loop: the variable declared by the initial part of the loop is only instantiated once.


Pages:
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320