Simplifying redundant cases within switch

So, one of the ways to shave some lines off of the switch statment is to look for cases that will be running the same code. For example, my main menu logic checks input against “menu”, “1”, “2”, “3”, and default. However, in cases 1, 2 and 3, they all run the same code:


                level = int.Parse(input);
                StartGame();
                break;

So instead of repeating that same code for each case, here’s a syntax that works:

    void RunMainMenu(string input)
    {
        switch (input)
        {
            case "menu":
                // if input is menu
                ShowMainMenu();
                break;
            case "1":
            case "2":
            case "3":
                level = int.Parse(input);
                StartGame();
                break;
            default:
                // if input is anything else
                Terminal.WriteLine("invalid input");
                break;
        }

    }

much less clutter.

Privacy & Terms