Note that if you
only capture this, no extra types are required??”the compiler just creates an instance
method to act as the delegate??™s action.
OK, so local variables aren??™t always local anymore. You may well be wondering what
I could possibly throw at you next??”let??™s see now, how about multiple delegates capturing
different instances of the same variable? It sounds crazy, so it??™s just the kind of
thing you should be expecting by now.
5.5.5 Local variable instantiations
On a good day, captured variables act exactly the way I expect them to at a glance. On
a bad day, I??™m still surprised when I??™m not taking a great deal of care. When there are
problems, it??™s almost always due to forgetting just how many ???instances??? of local variables
I??™m actually creating. A local variable is said to be instantiated each time execution
enters the scope where it??™s declared. Here??™s a simple example comparing two very
similar bits of code:
int single;
for (int i=0; i < 10; i++)
{
single = 5;
Console.WriteLine(single+i);
}
for (int i=0; i < 10; i++)
{
int multiple = 5;
Console.WriteLine(multiple+i);
}
156 CHAPTER 5 Fast-tracked delegates
In the good old days, it was reasonable to say that pieces of code like this were semantically
identical. Indeed, they??™d usually compile to the same IL. They still will, if there
aren??™t any anonymous methods involved.
Pages:
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318