C# dictionary store action/method

10,130

Solution 1

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)

Solution 2

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);
}
Share:
10,130
John
Author by

John

Updated on June 14, 2022

Comments

  • John
    John almost 2 years

    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?

    • SpruceMoose
      SpruceMoose over 6 years
      Yes. Why would it not be possible?
    • Manfred Radlwimmer
      Manfred Radlwimmer over 6 years
      Yes, quite simple actually. You can make the type of the value any delegate you want (e.g. Action, Predicate, etc.).
    • John
      John over 6 years
      Why would it not be possible to disable gravity? @Cal279
    • John
      John over 6 years
      I thought of Action<>, but wondered if this is the right point to get this one started.
    • Manfred Radlwimmer
      Manfred Radlwimmer over 6 years
      Because science is not that far yet. But lucky you - what you want is possible.
    • illug
      illug over 6 years
      Have a look at reflection
    • Manfred Radlwimmer
      Manfred Radlwimmer over 6 years
      Yes, Action<> can be stored within a dictionary. Upon retrieval you can execute it like a regular function, e.g. dict["123"](parameter)
    • Manfred Radlwimmer
      Manfred Radlwimmer over 6 years
      @illug Always a good topic, but seems like overkill in this particular situation.
    • John
      John over 6 years
      Thanks, @ManfredRadlwimmer. I'll take a look at this.