#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