#1,179 – Captured Variable’s Lifetime Matches Delegate

When a variable is captured by inclusion in a lambda expression, the lifetime of that variable becomes the lifetime of the delegate that the lambda is assigned to.

In the example below, we have a local variable whose scope is the body of the SomeFunction method.  We then use this local variable in a lambda expression that is assigned to a delegate instance.  After we exit SomeFunction, we can invoke the delegate and see that the variable defined in SomeFunction is still accessible.

        static Action aDelegate;

        static void Main(string[] args)
        {
            SomeFunction();

            // After call, invoke delegate to show
            // that magicNum is still alive
            aDelegate();

            Console.ReadLine();
        }

        static void SomeFunction()
        {
            int magicNum = 42;

            // Assign delegate to print value of local
            // variable
            aDelegate = () => Console.WriteLine(magicNum);
        }

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

4 Responses to #1,179 – Captured Variable’s Lifetime Matches Delegate

  1. Pingback: Dew Drop – September 10, 2014 (#1852) | Morning Dew

  2. Albert Chang says:

    This line:

    aDelegate = () => Console.WriteLine(magicNum);

    it should be:

    aDelegate = () => Console.WriteLine(magicNum);

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: