C# store functions with parameters in a List [closed]

I want to store functions with parameters in a List, so that I can call them at a later stage.

Let's say (this is rough code)

void Func1(int index)
{
Debug.Log("Func1"+index)
}

void Func2(int index)
{
Debug.Log("Func2"+index)
}
.
.
.

void Store(Func1(1))
{
}

void Replay(int position)
{
list[position](); // this calls the function with the parameter
}

• use a lambda expression: Action f = () => Func1 (1); f (); – trollingchar Dec 5 '19 at 6:55
• @trollingchar Sorry I quite not understand by what you mean. Can you please elaborate. Thanks – Hash Buoy Dec 5 '19 at 7:22

You declare that you have a list of actions:

List<Action> list;


Do not forget to initialize it:

list = new List<Action>();


Then, you create an action from the function using a lambda expression:

Action action = () => Func1(1);


And you add the action to the list:

list.Add(action);


You can, of course, inline the lambda expression:

list.Add(() => Func1(1));


Afterwards you can call the actions, for example, in a loop:

foreach (var action in list)
{
action.Invoke();
}


Actually, you do not need to use Invoke:

foreach (var action in list)
{
action();
}


Ah, yes, that works too:

list[position]();

• Thanks a lot for a detailed answer, will try it and let you know :) – Hash Buoy Dec 5 '19 at 7:34
• Works fine, thanks a lot !!! – Hash Buoy Dec 5 '19 at 12:39