C# Store functions in a Dictionary

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<>.

Leave a Comment