#1,186 – Capturing a foreach Iteration Variable in a Lambda Expression
September 19, 2014 3 Comments
If you capture a for loop iteration variable in a lambda expression, the value of the variable that the expression uses will be whatever the final value of the iteration variable is when the loop completes.
Capturing the iteration variable in a foreach loop works differently. When you capture the iteration variable in a foreach loop, the lambda expression has a copy of the iteration variable with the value that it had at the time that it was captured.
int[] primes = { 2, 3, 5, 7, 11, 13 }; List<Action> dels = new List<Action>(); // Capture foreach iteration variable foreach (int p in primes) dels.Add(() => Console.WriteLine(p)); foreach (Action a in dels) a();
Pingback: Dew Drop – September 19, 2014 (#1859) | Morning Dew
Pingback: The Daily Six Pack: September 22, 2014 - G3资讯网
Just FYI: Foreach works this way beginning C# 5, before it behaved like a for loop, see http://ericlippert.com/2009/11/12/closing-over-the-loop-variable-considered-harmful-part-one/