#1,179 – Captured Variable’s Lifetime Matches Delegate
September 10, 2014 4 Comments
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); }
Pingback: Dew Drop – September 10, 2014 (#1852) | Morning Dew
This line:
aDelegate = () => Console.WriteLine(magicNum);
it should be:
aDelegate = () => Console.WriteLine(magicNum);
Looks like the same thing to me. What’s the change that you’re suggesting?
🙂