This code is the reduced down version of the issue I'm having
public void MyMethod()
{
System.Action[] actions = new System.Action[5];
for (var i = 0; i < actions.Length; i++)
{
actions[i] = () => TestMethod(i);
actions[i]();
}
for (var i = 0; i < actions.Length; i++)
{
Console.WriteLine(i);
actions[i]();
}
}
public void TestMethod(int index)
{
// Just writing to the console for now
Console.WriteLine(index);
}
I'm expecting the output to be like this:
First for loop: 0,1,2,3,4 Second for loop: 0,1,2,3,4
but turns out it's actually like this: First for loop: 0,1,2,3,4 Second for loop: 5,5,5,5,5
No clue what's happening in the background machine code, but is is not saving the value itself?
I really need this additional passed in parameter action = () => foo(bar);
to work.
is there some way I can turn the i variable into just a value if that makes sense? I have a feeling it gets passed in as a reference and after the loop i is of course 5.
I thought in c# all value type variables get passed in as values instead of references. Thanks in advance for the help!!