#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
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.

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: