0

Lifetime of local variable declared inside a method is limited to the execution of that method. But in the following code sample lifetime of local variable index preserved after the execution of method .

class Program { static Action action; static void Main(string[] args) { setAction(); for (int i = 0; i < 5; i++) { action(); } Console.ReadLine(); } static void setAction() { var index = 5; action = () => { index++; Console.WriteLine("Value in index is {0}",index); }; } } 

The output of the program is this

Value in index is 6 Value in index is 7 Value in index is 8 Value in index is 9 Value in index is 10 

I can not understand how the values in variable index is preserved.

5
  • 1
    C# compiler creates class with variable index saved there, for each action() call it uses this variable. Read about closures: csharpindepth.com/Articles/Chapter5/Closures.aspx Commented Sep 10, 2017 at 18:35
  • It gets copied? Commented Sep 10, 2017 at 18:36
  • it is not local to the action since it is defined outside of it. Commented Sep 10, 2017 at 18:38
  • when capturing variable in closures, weird (meaning "not so clear") things happen Commented Sep 10, 2017 at 18:39
  • To get the result that you expect, bring SetAction inside for loop, then the value will not change since index variable will be re initialized, as new Action is created everytime Commented Sep 10, 2017 at 18:45

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.