#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

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: