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
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
See more on this question at Stackoverflow