#1,122 – It’s Okay to Capture Variables within a foreach Loop

Within a foreach loop, you capture an iteration variable when you save it for later use.  In versions of C# earlier than 5.0, this led to problems and unexpected behavior.  What ended up being captured was multiple copies of the last value of the iteration variable.

This has been changed in C# 5.0 so that you can capture an iteration variable within a foreach loop and get the expected behavior.

            string[] beatles = {"George", "John", "Paul", "Ringo"};

            List<Action> actionList = new List<Action>();
            List<string> guyList = new List<string>();

            foreach (string guy in beatles)
            {
                guyList.Add(guy);
                actionList.Add(() => Console.WriteLine(guy));
            }

            foreach (string guyInList in guyList)
                Console.WriteLine(guyInList);

            Console.WriteLine("===");

            foreach (Action a in actionList)
                a();

1122-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.

One Response to #1,122 – It’s Okay to Capture Variables within a foreach Loop

  1. Pingback: Dew Drop – June 23, 2014 (#1801) | Morning Dew

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: