#1,183 – How to Correctly Capture a for Loop Variable in a Lambda Expression

If you directly capture a for loop variable within a lambda expression, the value used when executing the expression will typically be the value of the variable at the time that the loop exits.  If you instead want to capture a variable whose value is the value of the for loop variable while the loop is executing, you can use a local variable.

            Action[] dels = new Action[3];

            // How to correctly capture for loop variable
            for (int i = 0; i < 3; i++)
            {
                int iLocal = i;
                dels[i] = () => Console.WriteLine(iLocal + 1);
            }

            // Prints 1/2/3
            foreach (Action d in dels)
                d();

1183-001

Advertisement