Closure capture (loop variables) in C# 5.0
Question:
In C# 5.0, issues with capturing closures in foreach loops have been resolved, ensuring that the correct values of loop variables are captured. However, the same problem still exists in the for loop. Why isn't this problem solved for both types of loops?
Answer:
The existing behavior in the for loop is logically sound. Although a foreach loop is similar to declaring a new variable for each iteration, a for loop has a unique structure, including an initializer, conditions, iterators, and a body.
The initializer in the for loop is executed only once, so it is logical to do the "variable instantiation" only once. Furthermore, there is no inherent assumption about the "initial" value of the variable for each loop iteration.
Consider the following example:
for (int i = 0, j = 10; i < 5; i++, j--) { Action action = () => Console.WriteLine(i, j); action(); }
In this case, if you solve this problem for a for loop, it will be difficult to determine its behavior.
The above is the detailed content of Why Doesn't C# 5.0's Captured Closure Fix Apply to For Loops?. For more information, please follow other related articles on the PHP Chinese website!