
CHAPTER 10 ■ DELEGATES, ANONYMOUS FUNCTIONS, AND EVENTS 271
PrintAndIncrement[] delegates = CreateDelegates();
for( int i = 0; i < 3; ++i ) {
delegates[i]();
}
}
}
The anonymous method inside the CreateDelegates method captures someVariable, which is a
local variable in the CreateDelegates method scope. However, since three instances of the anonymous
method are put into the array, three anonymous method instances have now captured the same
instance of the same variable. Therefore, when the previous code is run, the result looks like this:
0
1
2
As each delegate is called, it prints and increments the same variable. Now, consider what
effect a small change ...