Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to store functions in a dictionary?

Tags:

c#

dictionary

I have a message coming into my C# app which is an object serialized as JSON, when i de-serialize it I have a "Name" string and a "Payload" string[], I want to be able to take the "Name" and look it up in a function dictionary, using the "Payload" array as its parameters and then take the output to return to the client sending the message, is this possible in C#?

I've found a stack overflow answer here where the second part seems plausible but i don't know what I'm referencing with State

like image 840
James T Avatar asked May 22 '15 13:05

James T


People also ask

Can you store functions in dictionary?

Given a dictionary, assign its keys as function calls. Case 1 : Without Params. The way that is employed to achieve this task is that, function name is kept as dictionary values, and while calling with keys, brackets '()' are added.

Can you have functions in dictionaries Python?

In Python, everything is an object, so the dictionary can be passed as an argument to a function like other variables are passed.

What can you store in a dictionary?

It is flexible in that it allows a dictionary to contain keys of a wide variety of types. For example, the same dictionary can contain keys that are integers, floats, tuples, booleans, strings, and other types.


1 Answers

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 
like image 136
Jon Skeet Avatar answered Oct 12 '22 04:10

Jon Skeet