Lingxi
Lingxi

Reputation: 14987

Confusion about value capturing in C# lambda

To illustrate my confusion, see the following example:

int a = 0;
Action act = () => ++a;
act();
Console.WriteLine(a);

I have difficulty figuring out how modification to the captured variable within the lambda could possibly affect the local variable a. First of all, the implicitly generated lambda function object could not store a reference to the local variable a. Otherwise, if act is returned and invoked later, the referenced local variable a would already be vanished. A solution to this problem would be copy-by-value, either by copying the int value directly or through boxing, so that the function object would have its own copy the local variable a. But this doesn't explain the example just given. So, what is the underlying mechanism? Would it be that the seemingly local variable a is actually no longer a local variable, but translated by the compiler to be a reference to an int field within the generated lambda function object?

Upvotes: 4

Views: 492

Answers (1)

Andrey Ershov
Andrey Ershov

Reputation: 1803

The point here is closure. After compilation a is not a local variable anymore - it's a field of auto-generated class, both in function scope and in lambda.

Upvotes: 3

Related Questions