Prev | Current Page 307 | Next

Jon Skeet

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

All the space for local variables is allocated
on the stack at the start of the method, so there??™s no cost to ???redeclaring??? the variable
for each iteration of the loop. However, in our new terminology the single variable
will be instantiated only once, but the multiple variable will be instantiated ten
times??”it??™s as if there are ten local variables, all called multiple, which are created
one after another.
I??™m sure you can see where I??™m going??”when a variable is captured, it??™s
the relevant ???instance??? of the variable that is captured. If we captured
multiple inside the loop, the variable captured in the first iteration
would be different from the variable captured the second time round,
and so on. Listing 5.13 shows exactly this effect.
List list = new List();
for (int index=0; index < 5; index++)
{
int counter = index*10;
list.Add (delegate
{
Console.WriteLine(counter);
counter++;
}
);
}
foreach (ThreadStart t in list)
{
t();
}
list[0]();
list[0]();
list[0]();
list[1]();
Listing 5.13 creates five different delegate instances C??”one for each time we go
around the loop. Invoking the delegate will print out the value of counter and then
increment it. Now, because counter is declared inside the loop, it is instantiated for
each iteration B, and so each delegate captures a different variable.


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