14 (even with the
annotations)? Frankly it would take me a little while??”longer than I like to spend
understanding code. Just as an exercise, though, let??™s look at what happens.
First let??™s consider the outside variable B. The scope it??™s declared in is only entered
once, so it??™s a straightforward case??”there??™s only ever one of it, effectively. The inside
variable C is a different matter??”each loop iteration instantiates a new one. That
means that when we create the delegate instance D the outside variable is shared
between the two delegate instances, but each of them has its own inside variable.
After the loop has ended, we call the first delegate instance we created three times.
Because it??™s incrementing both of its captured variables each time, and we started off
with them both as 0, we see (0,0), then (1,1), then (2,2). The difference between the
two variables in terms of scope becomes apparent when we execute the second delegate
instance. It has a different inside variable, so that still has its initial value of 0,
but the outside variable is the one we??™ve already incremented three times. The output
from calling the second delegate twice is therefore (3,0), then (4,1).
NOTE How does this happen internally? Just for the sake of interest, let??™s think
about how this is implemented??”at least with Microsoft??™s C# 2 compiler.
Pages:
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322