Can't pass a variable as method parameter?

OK, this is a tricky one for me…

I’m trying to add a OnClick listener to my buttons:

int i = 0;
            foreach (var optionString in optionsCollection.options)
            {

                testButtons*.onClick.AddListener(() => SetOption(i));*

i++;
}
But for some reason when I click the button I get this error:
ArgumentOutOfRangeException: Argument is out of range.
Parameter name: index
System.Collections.Generic.List1[System.Collections.Generic.KeyValuePair2[System.String,System.String]].get_Item (Int32 index) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/List.cs:633)
Yarn.VirtualMachine.m__0 (Int32 selectedOption)
Yarn.Unity.PopulateUI.SetOption (Int32 selectedOption) (at Assets/Scripts/PopulateUI.cs:116)
Yarn.Unity.PopulateUI+c__Iterator5.<>m__0 () (at Assets/Scripts/PopulateUI.cs:93)
UnityEngine.Events.InvokableCall.Invoke (System.Object[] args)

But if I go like this:
int i = 0;
foreach (var optionString in optionsCollection.options)
{

if (i == 0)
{
testButtons*.onClick.AddListener(() => SetOption(0));*
}else
{
testButtons*.onClick.AddListener(() => SetOption(1));*
}
i++;
}
…it works! My question is why I can’t pas the int i as a parameter of the function SetOption? Why if I hardcode the number it works?
Thank you

There’s no “problem” with what you are doing here, except that this code works probably a bit differently than what one would easily expect.

In C#, when you write a closure like that, it is not the value of i that gets captured in the anonymous method, but it’s the variable itself. This almost makes it seem like the fundamentals of value types vs. reference types gets broken.

After you finish that loop, i has the value optionsCollection.options.Count (or .Length) and whenever you finally click your buttons, all of them call SetOption with that same value.

If you want to prevent this, you have to pass to the closure an integer that you don’t change anywhere later.

int i = 0;
foreach (var optionString in optionsCollection.options)
{
    var temp = i;
     testButtons*.onClick.AddListener(() => SetOption(temp));*

i++;
}