Anonymous function and local variables

Say you have a button on your form. You added an anonymous function to the Click

event button :

void Test()
{
  int x = 10;
  btn.Click += (sender, e) => { MessageBox.Show(x.ToString()); };
}

      

This works as expected and displays 10; means that it can access local variables. My question is: how and why? How does an anonymous function access the local context?

The actual problem I'm dealing with is that I need to update (so to speak) this anonymous function to a regular function (event handler). But this means that I will lose access to the x variable. I cannot pass it as a parameter, because then I cannot attach it to the event Click

(signature mismatch). I can get around this by creating globals and all, but how do anonymous functions allow you to access things beyond their scope?

+3


source to share


1 answer


Half of the anonymous functions are that they can capture the context in which they are specified. It's very convenient to be able to do this - that's the "why" part.

The compiler way is to create a new class when needed. This way your code will be converted to something like:

void Test()
{
    TestHelper helper = new TestHelper();
    helper.x = 10;

    btn.Click += helper.Method;
}

private class TestHelper
{
    public int x = 10;

    public void Method(object sender, EventArgs e)
    {
        MessageBox.Show(x.ToString());
    }
}

      

Each use x

internally is Test

converted to use helper.x

for the corresponding instance. This is how variables with different lifetimes are covered. For example, suppose you had a loop like this:



for (int i = 0; i < 10; i++)
{
    int x = i;
    // Use with some anonymous function
}

      

then it will create a new instance TestHelper

for each iteration of the loop ... whereas if it x

were declared outside of the loop, then there would be only one instance in which all the anonymous functions would effectively share.

When it's simple this

that has been captured, the compiler creates an instance method on the existing class instead of creating a helper class. When there are different scopes with potentially numerous anonymous functions that capture different variables, things can get complicated, and some helper classes have references to instances of other helper classes, etc.

+10


source







All Articles