It??™s
easy to get this wrong! If you want to capture the value of a loop variable for that particular
iteration of the loop, introduce another variable within the loop, copy the loop
variable??™s value into it, and capture that new variable??”effectively what we??™ve done in listing
5.13 with the counter variable.
For our final example, let??™s look at something really nasty??”sharing some captured
variables but not others.
5.5.6 Mixtures of shared and distinct variables
Let me just say before I show you this next example that it??™s not code I??™d recommend.
In fact, the whole point of presenting it is to show how if you try to use captured variables
in too complicated a fashion, things can get tricky really fast. Listing 5.14 creates
two delegate instances that each capture ???the same??? two variables. However, the story
gets more convoluted when we look at what??™s actually captured.
ThreadStart[] delegates = new ThreadStart[2];
int outside = 0;
for (int i=0; i < 2; i++)
{
int inside = 0;
delegates[i] = delegate
{
Console.WriteLine ("({0},{1})",
outside, inside);
outside++;
inside++;
};
}
ThreadStart first = delegates[0];
ThreadStart second = delegates[1];
first();
first();
first();
second();
second();
Listing 5.14 Capturing variables in different scopes. Warning: nasty code ahead!
Be careful
with
for/foreach
loops!
B Instantiates
variable once
C Instantiates
variable
multiple times
D
Captures variables
with anonymous
method
158 CHAPTER 5 Fast-tracked delegates
How long would it take you to predict the output from listing 5.
Pages:
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321