Say I have a C# method like this
public void MyMethod()
{
int i = 0;
var thread = new Thread(() =>
{
Thread.Sleep(100);
if (i == 0)
{
Console.WriteLine("Value not changed and is {0}", i);
}
else
{
Console.WriteLine(" Value changed to {0}.", i);
}
});
thread.Start();
i = 1;
}
Here method creates a thread which access the local variable created in method. By the time it access this variable the method has finished and thus a local variable i should not exist. But the code runs without any trouble. As per my understanding local variable do not exist after the method block finishes.I am not able to get this.
As per my understanding local variables do not exist after the method block finishes.I am not able to get this.
Your understanding is simply wrong. The defining characteristic of a local variable is that its name is only in scope inside its declaring block. That's why it is called a "local" variable -- because its name is only visible locally.
You believe the falsehood that "local" means "short lived". That is incorrect; a local variable is short lived when it can be, but there are three situations in which it cannot be: when it is the closed-over outer variable of an anonymous function, when it is in an iterator block, or when it is in an async block.
Coincidentally your question was the subject of my blog last week; see it for more details:
http://blogs.msdn.com/b/ericlippert/archive/2012/01/16/what-is-the-defining-characteristic-of-a-local-variable.aspx
This works because the compiler rewrites your code to use a closure.
Since you use the variable within a lambda, the variable ends up getting changed to be a member of a class. The compiled code doesn't contain a local variable for i - even though you wrote it that way. Instead, it rewrites your code to use a compiler-generated class which contains an Int32 as a member variable, and the "local code" as well as the lambda refer to this class member instead.
For details, see this blog post on closures which gives you a rough sense of what the compiler does here.
That's called a closure.
It extends local variables beyond the lifetime of the method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With