frenchie
frenchie

Reputation: 51997

How to map strings to methods with a dictionary

I have some code that looks like this:

switch(SomeString)
{
   case "Value1":
        MethodA();
        break;

   case "Value2":
        MethodB();
        break;
   ... 40 other cases
}

How could I rewrite this code using a dictionary of <string, method> so that for instance the key would be "Value1" and the value would be MethodA() and that I'd write something that says "execute the function whose name is the value of key SomeString". Note that all the methods take no argument and don't have any return.

Upvotes: 6

Views: 5815

Answers (2)

KevinS
KevinS

Reputation: 252

Declare your dictionary:

Dictionary<string,Action> methodMap = new Dictionary<string,Action>();;

Add entries:

methodMap["Value1"] = MethodA; ...

Execute:

methodMap["Value1"] ();

Upvotes: 3

Enigmativity
Enigmativity

Reputation: 117134

You could do this:

var actions = new Dictionary<string, Action>()
{
    { "Value1", () => MethodA() },
    { "Value2", () => MethodB() },
};

You would invoke like this:

actions["Value1"]();

Now you could simplify to this:

var actions = new Dictionary<string, Action>()
{
    { "Value1", MethodA },
    { "Value2", MethodB },
};

But I'd suggest going with the first option as it allows you to do this:

var hello = "Hello, World!";
var actions = new Dictionary<string, Action>()
{
    { "Value1", () => MethodA(42) },
    { "Value2", () => MethodB(hello) },
};

Upvotes: 12

Related Questions