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.