#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

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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

  1. Pingback: Dew Drop – September 8, 2014 (#1850) | Morning Dew

Leave a comment