0

If I was looking at the following code as Javascript code, it would make sense...but how is it that the call action() in Main doesn't yield a NullReferenceException for i? Did the Action grab a JavaScript context like thing? Thanx in advance to all.

public class Program
{
    static void Main(string[] args)
    {
        var p = new Program();
        var action = p.method();
        action();
        Console.ReadKey();

    }

    public Action method()
    {
        var i = 6;
        Action action = () => Console.WriteLine(i);
        i++;
        return action;
    }

}

OUTPUT>>7

1
  • 1
    The word you're looking for is 'closure', rather than context. There's quite a bit of information on the topic if you search for "C# closure", but in essence, i is extracted out of method into its closure, which allows it to persist after leaving the scope of method. Commented Aug 1, 2017 at 0:04

1 Answer 1

0

The lambda created in method captures any variables referenced inside the lambda.

See this article: https://blogs.msdn.microsoft.com/matt/2008/03/01/understanding-variable-capturing-in-c/

Sign up to request clarification or add additional context in comments.

4 Comments

if in the article you link the variable 'name' were a primitive type, the Capture class would get a copy and any changes in the calling method would not be reflected in Capture class. Yet they are? I know, the Capture class was simply an idea that I assume was geared towards reference types.
Not true - all references to what was previously a local are now references to the field of the Capture class. The type of the variable/field doesn't matter.
But the field of the Capture changes when we change the 'name' in the main method...and this happens after the Capture class was created with its own copy of that variable?
If you check the example (scroll down), the main function is changed by the compiler to reference the Capture instance field instead as it replaces the local variable.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.