Modified Closures should be a language bug
Summary:
When you define a closure within the context of a loop, the closure is defined with the final value of anything iterated over in the loop. If this sounds strange, that’s because it is. See the simple example below.
The Code:
Download: [C# File] [Zipped Console Project]
The curious part is the simple PrintMe delegate that takes no arguments & returns nothing.
delegate void PrintMe();
Within the foreach loop where we iterate over the int array {1,2,3,4}, we define a closure (delegate) that merely prints i the integer being iterated.
(PrintMe)delegate(){ Console.WriteLine(i); }
The Output:
You might expect the output, when we invoke each PrintMe delegate to be 1, 2, 3 & 4, but instead the output is 4, 4, 4, 4.
Solution:
By copying the value of i to a local variable j and the expected result is the actual result. We iterate over the integer array { 1,2,3,4 } and we print { 1,2,3,4 }.
This one line is the strange fix.
int j = i;
Just use j in the closure instead of i
(PrintMe)delegate()
{
Console.WriteLine(j);
}
Download: [C# File] [Zipped Console Project]