#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