Is it possible to store functions in a dictionary?

It sounds like you probably want something like:

Dictionary<string, Func<string[], int>> functions = ...;

This is assuming the function returns an int (you haven’t specified). So you’d call it like this:

int result = functions[name](parameters);

Or to validate the name:

Func<string[], int> function;
if (functions.TryGetValue(name, out function))
{
    int result = function(parameters);
    ...
}
else
{
    // No function with that name
}

It’s not clear where you’re trying to populate functions from, but if it’s methods in the same class, you could have something like:

Dictionary<string, Func<string[], int>> functions = 
    new Dictionary<string, Func<string[], int>>
{
    { "Foo", CountParameters },
    { "Bar", SomeOtherMethodName }
};

...

private static int CountParameters(string[] parameters)
{
    return parameters.Length;
}

// etc

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)