© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•2y ago•
6 replies
Ninja Kirby

✅ 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?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

I dont know what is wrong
C#CC# / help
4w ago
❔ Dont Know What To Do?
C#CC# / help
3y ago
✅ I dont know what im doing wrong?!
C#CC# / help
3y ago
Dont know how to get this Mem module
C#CC# / help
16mo ago