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?
Asked
Active
Viewed 1.3k times
2

John
- 197
- 1
- 2
- 22
-
1Yes. Why would it not be possible? – SpruceMoose Oct 18 '17 at 10:34
-
Yes, quite simple actually. You can make the type of the value any delegate you want (e.g. `Action`, `Predicate`, etc.). – Manfred Radlwimmer Oct 18 '17 at 10:35
-
Why would it not be possible to disable gravity? @Cal279 – John Oct 18 '17 at 10:36
-
I thought of `Action<>`, but wondered if this is the right point to get this one started. – John Oct 18 '17 at 10:36
-
Because science is not that far yet. But lucky you - what you want is possible. – Manfred Radlwimmer Oct 18 '17 at 10:36
-
Have a look at reflection – illug Oct 18 '17 at 10:37
-
1Yes, `Action<>` can be stored within a dictionary. Upon retrieval you can execute it like a regular function, e.g. `dict["123"](parameter)` – Manfred Radlwimmer Oct 18 '17 at 10:37
-
@illug Always a good topic, but seems like overkill in this particular situation. – Manfred Radlwimmer Oct 18 '17 at 10:38
-
Thanks, @ManfredRadlwimmer. I'll take a look at this. – John Oct 18 '17 at 11:02
2 Answers
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