How to create a list of methods then execute them?

This is a great use case for the Action generic delegate.

List<Action> functions = new List<Action>();
functions.Add(Move);

foreach (Action func in functions)
   func();

If you need parameters, I would use lambdas to abstract them away:

List<Action> functions = new List<Action>();
functions.Add(Move);
functions.Add(() => MoveTo(1, 5));

foreach (Action func in functions)
   func();

A delegate is akin to function pointers from C++, it holds what a function "is" (not a return value like in your example) so you can call it just like a regular function. The Action generic delegate takes no parameters and returns nothing, so it is ideal for generic "call these functions".

MSDN for Action: Action Delegate

For more on the different types of delegates provided by.NET: https://stackoverflow.com/a/567223/1783619


I'm not sure if this outside the scope of the original question (or will help anyone else), but I kept coming back to this page in my own search of how to create a list of return-type functions to iterate and execute. I ended up using the List<Func<T>> to create a list of type methods-

        bool RTrue()
        {
            Console.WriteLine("RETURNS TRUE");
            return true;
        }

        bool RFalse()
        {
            Console.WriteLine("RETURNS FALSE");
            return false;
        }

        List<Func<Boolean>> functions = new List<Func<Boolean>>();
        functions.Add(RTrue);
        functions.Add(RFalse);

        foreach (Func<Boolean> func in functions)
        {
            if (func() == true)
            {
                Console.WriteLine("IT WORKS");
            }
        }

Further info on Func usage- What is Func, how and when is it used


You can use delegates. Create a list of delegates. Then, for each method you want to add to the list, create a delegate and add to the list.

 List<Delegate> methods = new List<Delegate>();

 // creates an Action delegate implicitly
 methods.Add((Action)Move);

Tags:

C#

Methods

List