Powerful Switch

Hi All,

I think the Switch statement can be really useful, for example, you can set things based on multiple cases without too much repeated code. In this code, a Difficulty enum is set based on the level. It also shows how you can set other things but still “fall through” using a goto statement. Goto is rarely used but I think it is safe in a Switch providing you go to later cases only.

void StartGame()
        {
            Terminal.ClearScreen();
            currentScreen = Screen.Password;

            switch (level)
            {
                case 0:
                    difficulty = Difficulty.Tutorial;
                    break;
                case 1:
                case 2:
                    difficulty = Difficulty.Easy;
                    break;
                case 3:
                    isBonusLevel = true;
                    goto case 5;
                case 4:
                    isBonusLevel = false;
                    goto case 5;
                case 5:
                    difficulty = Difficulty.Medium;
                    break;
            }
}

This gives;

0 - Tutorial - isBonusLevel == False
1 - Easy - isBonusLevel == False
2 - Easy - isBonusLevel == False
3 - Medium - isBonusLevel == True
4 - Medium - isBonusLevel == False
5 - Medium - isBonusLevel == False

3 Likes

Awesome job with the code! It is looking really good!

Privacy & Terms