0

I have this code:

for (int i = 0; i < 7; ++i)
    Roption.DropDownItems.Add(string.Concat("Item &", i), null, delegate { Reset(i); });

where Reset() is called when the dropdown item is clicked.

The problem is that no matter which dropdown item is clicked, the argument passed to Reset is 7 (the value of i after the loop terminates), not the value of i when the Roption.DropDownItems.Add function is called. What causes this behavior and how can it be fixed? (I don't really want to hard code 0 through 6 in seven otherwise identical statements).

limits
  • 295
  • 4
  • 12

1 Answers1

2

Your problem here is that when you are creating the delegates in a loop, all objects will be passed by reference. This means that regardless of whether they are value-type or reference-type objects, they will still get passed by reference.

So what does this mean for your code? Well, as the loop iterates through, all of the Reset method calls that have a copy of i have a reference to the same one. So, as the value of i increases, so does the value for every single reference.

Closures Explained

Snoop
  • 1,046
  • 1
  • 13
  • 33