✅ 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:
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
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.
is using this "hack" where i just use idx instead bad
yeah it def is
thanks bro
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