#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

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: