#1,186 – Capturing a foreach Iteration Variable in a Lambda Expression

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();

1186-001

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

3 Responses to #1,186 – Capturing a foreach Iteration Variable in a Lambda Expression

  1. Pingback: Dew Drop – September 19, 2014 (#1859) | Morning Dew

  2. Pingback: The Daily Six Pack: September 22, 2014 - G3资讯网

  3. Rico says:

    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/

Leave a comment