reusing switch statement logic

c#, switch-statement

Solution

You could also have a Dictionary (or Func instead of Action) or something like that (considering your functions have a similar signature). Then you could instead of using a switch, you could have something like:

public class MyClass
{
    Dictionary<string, Action> myDictionary;

    public MyClass()
    {
        BuildMyDictionary();
    }

    private Dictionary<int, Action<int, int>> BuildMyDictionary()
    {
        myDictionary.Add("x", DoSomethingX);
        myDictionary.Add("y", DoSomethingY);
        myDictionary.Add("z", DoSomethingZ);
        myDictionary.Add("w", DoSomethingW);
    }


    public void DoStuff()
    {
        string whatever = "x"; //Get it from wherever
        //instead of switch
        myDictionary[t]();
    }
}

I answered a similar question here with a similar example.

Also, try using enums instead of strings in your switch statement.

Problem

What is the best way to reuse switch logic. I have this switch statement that keeps appearing in my code. Rather then copy paste it I would like to make a function that calls other delegates and pass these delegates in as parameters. Or is there a better way? Function 1: ``` switch (test) { case "x": DoSomethingX(); break; case "y": DoSomethingY(); break; case "z": DoSomethingZ(); break; } ``` Function 2: ``` switch (test) { case "x": DoSomethingXxxx(); break; case "y": DoSomethingYyyy(); break; case "z": DoSomethingZyyy(); break; } ```

Original source

Related problems