Why does the following code print 11 twice?
int i = 10; Action fn1 = () => Console.WriteLine(i); i = 11; Action fn2 = () => Console.WriteLine(i); fn1(); fn2();
Exit 11 11
According to the answers in this post - How do I say lambda functions to capture a copy instead of a reference to C #? - lambda transferred to class with copy of captured variable. If so, should my sample not print 10 and 11?
Now that the lambda is capturing by reference, how does it affect the lifetime of the captured variable. For example, suppose the above code snippet was in a function and the scope was global for the variable:
class Test { Action _fn1; Action _fn2; void setActions() { int i = 10; _fn1 = () => Console.WriteLine(i); i = 11; _fn2 = () => Console.WriteLine(i); } static void Main() { setActions(); _fn1(); _fn2(); } }
In this case, the variable I did not go out of scope with the action? So, the actions left with a link to the dangling pointer?
closures c # lambda
Sumith
source share