C# Store functions in a Dictionary

chi picture chi · Nov 20, 2010 · Viewed 91k times · Source

How do I create a Dictionary where I can store functions?

Thanks.

I have about 30+ functions which can be executed from the user. I want to be able to execute the function this way:

   private void functionName(arg1, arg2, arg3)
   {
       // code
   }

   dictionaryName.add("doSomething", functionName);

    private void interceptCommand(string command)
    {
        foreach ( var cmd in dictionaryName )
        {
            if ( cmd.Key.Equals(command) )
            {
                cmd.Value.Invoke();
            }
        }
    }

However, the function signature is not always the same, thus having different amount of arguments.

Answer

Darin Dimitrov picture Darin Dimitrov · Nov 20, 2010

Like this:

Dictionary<int, Func<string, bool>>

This allows you to store functions that take a string parameter and return boolean.

dico[5] = foo => foo == "Bar";

Or if the function is not anonymous:

dico[5] = Foo;

where Foo is defined like this:

public bool Foo(string bar)
{
    ...
}

UPDATE:

After seeing your update it seems that you don't know in advance the signature of the function you would like to invoke. In .NET in order to invoke a function you need to pass all the arguments and if you don't know what the arguments are going to be the only way to achieve this is through reflection.

And here's another alternative:

class Program
{
    static void Main()
    {
        // store
        var dico = new Dictionary<int, Delegate>();
        dico[1] = new Func<int, int, int>(Func1);
        dico[2] = new Func<int, int, int, int>(Func2);

        // and later invoke
        var res = dico[1].DynamicInvoke(1, 2);
        Console.WriteLine(res);
        var res2 = dico[2].DynamicInvoke(1, 2, 3);
        Console.WriteLine(res2);
    }

    public static int Func1(int arg1, int arg2)
    {
        return arg1 + arg2;
    }

    public static int Func2(int arg1, int arg2, int arg3)
    {
        return arg1 + arg2 + arg3;
    }
}

With this approach you still need to know the number and type of parameters that need to be passed to each function at the corresponding index of the dictionary or you will get runtime error. And if your functions doesn't have return values use System.Action<> instead of System.Func<>.