✅ what is this? i dont know what to call this.

I'm making the game "simon" in winforms, and i ran into a 'problem'. In my game class, there's 2 lists of integers, the event sequence (the one the player should input) and the player input (the one the player actually inputs.) Whenever the player clicks a corresponding button, I add that button's index to the player inputs list. However, I do this via a lambda expression within a for loop as shown here:
for (int i = 0; i < 4; i++)
{
int idx = i;

SimonButton btn = SimonButtons[idx];

btn.MouseClick += (sender, e) =>
{
if (btn.IsLocked)
return;

_playerInputs.Add(i); // always results in adding 4 if I use i but not idx?? ????????
Console.WriteLine(i);
Console.WriteLine(idx);

_gameOver = IsGameOver();
};
}
for (int i = 0; i < 4; i++)
{
int idx = i;

SimonButton btn = SimonButtons[idx];

btn.MouseClick += (sender, e) =>
{
if (btn.IsLocked)
return;

_playerInputs.Add(i); // always results in adding 4 if I use i but not idx?? ????????
Console.WriteLine(i);
Console.WriteLine(idx);

_gameOver = IsGameOver();
};
}
why is it that if I put i as the .Add() parameter, it's always 4, but not idx, which is always i anyway?
3 Replies
TheBoxyBear
TheBoxyBear5mo ago
When referencing an outside variable in a lambda, it gets captured as a reference to the variable rather than through its value at the time. In this case, the loop runs to the end and by the time you click the button, i is 4. For sharing event handlers, you can put the index in button's respective Tag property and read it from the fixed click handler.
Green Skibidiby
Green Skibidiby5mo ago
is using this "hack" where i just use idx instead bad yeah it def is thanks bro
TheBoxyBear
TheBoxyBear5mo ago
You can loop through the buttons to subscribe to the event if the subscription should change at runtime. If not, just assign it in the designer