Dynamically generating buttons calling lambda function - variable area

I have a situation where I have one someFunction(int), and I need to generate soft buttons nthat will call it. This means that I want to create buttons B1, B2... Bnthat cause someFunction(1), someFunction(2)... someFunction(n)when pressed.

This is how I tried to do this (semi-pseudo-code):

for (int i = 1; i <= n; i++) {
  Button b = new Button();
  b.Caption = "Value " + n; // non-WPF: b.Text = "Value " + n;
  b.Click += (sender, event) => {
    someFunction(i);
  }
}

What bothers me is that when I click on the first button (B1), with a debugger above someFunction(i), it tells me what it calls someFunction(n + 1).

I am not sure why this is so, or how to fix it. The approach I use is to use instead someFunction(i), someFunction(int.Parse(i.ToString())(to create a copy i). But that seems shady to me because integers must be value types.

+3
source share
2 answers

I believe that you understand WHY this is happening. The problem is that it captures the variable i, not its value. The workaround that seems best (without toString and int.parse) to me is to declare another local var that copiesi

for (int i = 1; i <= n; i++) {
Button b = new Button();
  b.Caption = "Value " + n; // non-WPF: b.Text = "Value " + n;
  int locali = i;
  b.Click += (sender, event) => {
    someFunction(locali);
  }
}

Thus, the captured variable will be locali, and it will remain unchanged in the loop.

+2
source

Stormbreaker , .

# lambda, , ?

+1

All Articles