#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

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

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 comment