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.

ramanmittal
  • 91
  • 1
  • 11
  • 1
    C# compiler creates class with variable index saved there, for each action() call it uses this variable. Read about closures: http://csharpindepth.com/Articles/Chapter5/Closures.aspx – ingvar Sep 10 '17 at 18:35
  • It gets copied? – arrowd Sep 10 '17 at 18:36
  • it is not local to the action since it is defined outside of it. – Peter Bons Sep 10 '17 at 18:38
  • when capturing variable in closures, weird (meaning "not so clear") things happen – Gian Paolo Sep 10 '17 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 – Mrinal Kamboj Sep 10 '17 at 18:45

0 Answers0