2

I have a dictionary with string keys, e.g. 123456789. Now at some other point inside my application, I want my dictionary to look this key up and either run the method itself (stored along the key) or somehow return the function so I can manually add parameters. Is this even possible?

John
  • 197
  • 1
  • 2
  • 22

2 Answers2

6

You need to create a dictionary<string, Action>, this would be for no parameters.

e.g.

static class MyActions {
  static Dictionary<string,Action> wibble = new Dictionary<string,Action>();
}

I've used static, its not necessary if you can pass the reference around/retrieve the reference.

then to add action...

MyActions.wibble["123456789"] = () => { // do action };

or reference a no parameter method

MyActions.wibble["123456789"] = () => MyMethod;

then to call it;

MyActions.wibble["123456789"]()

Assuming the key exists, you can use try get or even MyActions.wibble["123456789"]?.Invoke()

If you need parameters, make the dictionary of type Action<T> or Action<T1, T2> etc depending on the number of parameters.

eg wibble = new Dictionary<string,Action<int>>()

and then wibble["123456789"] = x => {action with x}

and wibble["123456789"](42)

Bob Vale
  • 18,094
  • 1
  • 42
  • 49
5

Sounds like a simple task. (Doesn't include sanity checks)

Dictionary<string,Action<object>> dict;

public Action<object> GetFunction(string key)
{
    return dict[key];
}

public void CallFunction(string key, object parameter)
{
    dict[key](parameter);
}
Manfred Radlwimmer
  • 13,257
  • 13
  • 53
  • 62