#1,178 – Captured Variables Are Evaluted when a Delegate Is Invoked

A captured variable is a variable declared outside of the scope of a lambda expression, but used within the expression.

            int magicNum = 20;
            Func<int, int> mulByMagic = i => i * magicNum;

            Console.WriteLine(mulByMagic(10));  // 200

Note that the value used for a captured variable is whatever value is current when the associated delegate is invoked, rather than the value that the variable had when the lambda was defined.

            int magicNum = 20;
            Func<int, int> mulByMagic = i => i * magicNum;

            Console.WriteLine(mulByMagic(10));  // 200

            magicNum = 100;
            Console.WriteLine(mulByMagic(10));  // 1000