user1060500
user1060500

Reputation: 1535

Delegate in method using variables in scope of method but outside delegate scope

I wrote some sample code where I have an Action delegate declared in a method body where two params are passed and then consumed by the delegate code without those params being passed into the delagte. It seems cleaner to me to explictely pass in these params to the delegate too, but in this case I am not, and this code would work fine.

I am wondering how .NET keeps these references available in the export delegate that is now running on a new thread.

    public void MyMethod(string name, ComplexObject myObj)
    {

    Action export = () => {
       //do something with name
       name = name + name;
       //do something with complex reference object
        myObj.SomeMethod(name);
    };

    // do more work
    // example launch export on a new thread
    System.Threading.Thread newThread = new System.Threading.Thread(new System.Threading.ThreadStart(export));
    newThread.Start();
    }

Upvotes: 3

Views: 1042

Answers (1)

Mr. TA
Mr. TA

Reputation: 5359

The compiler creates a special type that keeps those variables. Then, instead of storing those variables on the stack, it instantiates an instance of that type every time you call that method. Then, the anonymous delegates use a reference to that new instance to get access to those variables.

Upvotes: 3

Related Questions