C # lambda expression, scope variable value

Hi I'm trying to write a lambda for an event handler. therefore, I can provide more information for the method that is being called.

so i do:

button.Click+=new EventHandler ((object sender, EventArgs args) => 
{ button_click (i, sender, args); });

Where:

public void button_click (int i, object sender, EventArgs eventArgs)

ok, so this works the same as calling the get method, but iit is always the last known value i, I really want the value at the point where the lambda goes to the event. How do you do this?

thank

+3
source share
1 answer

Just create a copy of the variable:

int currentI = i;
button.Click+=new EventHandler ((object sender, EventArgs args) => 
    { button_click (currentI, sender, args); });

Please note that you have a certain number of cracks there. You can write it easier:

int currentI = i;
button.Click += (sender, args) => button_click(currentI, sender, args);

Personally, I renamed the method button_clickto comply with the .NET naming conventions.

+5
source

All Articles