0

So I need to build dynamically a set of Actions with a foreach, something like this:

Action<object[]> actions;
int index = -1;
foreach(var item in itemCollection)
{
    actionsParametersArray[++index] = aParameter;
    actions += x => Console.WriteLine(index);
    actions += x => DoAction((int)actionsParametersArray[index]);
    actionsParametersArray[++index] = otherParameter;
    actions += x => DoOtherAction((MyCustomClass)actionsParametersArray[index]);
}

The problem is that when the actions get called they ALL use the last index value, f.i. if there are 10 items in itemCollection, all actions will try to take actionsParametersArray[19] as their parameter.

I thought that I read somewhere that types as int are always passed by value, but it seems that the value are be passed as reference so the last value of index is the only one that are working in all cases. So I supposed that was the error. Therefore, I thought that if I defined a new variable inside the block it will pass the variable to "value":

int parIndex = -1;
foreach(var item in itemCollection)
{
    int index;
    actionsParametersArray[++parIndex] = aParameter;
    index = parIndex;
    actions += x => DoAction((int)actionsParametersArray[index]);
    actionsParametersArray[++parIndex] = otherParameter;
    index = parIndex;
    actions += x => DoOtherAction((MyCustomClass)actionsParametersArray[index]);
}

It doesn't work either, it's the same but it just take the last value of one iteration (in this case, the parameter indexes would be 1, 3, 5...).

It only works if I create a new variable for each new Action (I've also read this question which gives the same answer, specifically Mong Zhu answer), which is not the ideal solution, honestly, since I have several iterations and actions per iteration... I'd need a lot of variables.

Are there any other solution to this?

Nox
  • 231
  • 1
  • 5
  • 16
  • You have a captured loop variable, therefore always getting the last value when action is invoked – Pavel Anikhouski Feb 22 '20 at 11:47
  • 1
    @PavelAnikhouski It seems that it answer the question... there's no other way but to create a proxy variable each time, or to find another way of create the actions. I'll read that Jon Skeet article about closures referenced in that question anyway. – Nox Feb 22 '20 at 12:21

0 Answers0