#1,182 – Capturing a for Loop Variable in a Lambda Expression

If you capture a variable in a lambda expression that is declared within the initializer of a for loop, the results may not be what you expect.  Recall that the value of a captured variable is evaluated when a delegate is invoked, rather than when it is assigned.  If you therefore invoke the delegate after all iterations of the loop have executed, the value of the captured variable will be whatever the final value of the variable was.

Below, notice that the same value is displayed during each invocation of the delegate.

            Action[] dels = new Action[3];

            for (int i = 0; i < 3; i++)
                dels[i] = () => Console.WriteLine(i + 1);

            // Prints 4/4/4, rather than 1/2/3
            foreach (Action d in dels)
                d();

1182-001

Advertisement