#1,177 – Lambda Expressions Can Reference Variables Declared Outside of Expression

A lambda expression can make use of its own parameters and local variable declarations.  For example:

            Action<int> act1 = (num) =>
            {
                for (int i = num; i < num + 2; i++)
                {
                    int result = i * 2 - 1;
                    Console.WriteLine(string.Format("{0}, {1}", i, result));
                }
            };

A lambda expression can also make use of a local variable or parameter declared outside of the lambda expression. For example:

        static void Main(string[] args)
        {
            DoSomething(4);
            Console.ReadLine();
        }

        static void DoSomething(int someParam)
        {
            int magicNum = 2;

            Action<int> act1 = (num) =>
            {
                for (int i = num; i < num + (magicNum * someParam); i++)
                {
                    int result = i * 2 - 1;
                    Console.WriteLine(string.Format("{0}, {1}", i, result));
                }
            };

            act1(5);
        }

1177-001