Beginning C# - Part 11: Switch Statement | Ray Wenderlich

This video covers the usage of the switch statement in C#.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/3247-beginning-c/lessons/11

I guess i didn’t undestood completly the concept of the switch case, here i my code i wanted to have 3 cases, one for player one, one for player two and one for more players and also one for invalid numbers as well.

private void OnDisable()
{
    switch (playerCont)
    {
        case 1:
            Debug.Log("Hello player one");
            break;
        case 2:
            Debug.Log("Hello player one and two");
            break;
        case 3:
            if (playerCont >= 2)
            {
                Debug.Log("Hello players");
            }
            break;
        default:
            Debug.Log("Please enter a valid number");
            break;
    }
}

The code works for numbers one to 3, however For 4 and up the code just fire the “Invalid number”.
What i am missing?

Cheers :slight_smile:

@rafaelriva The switch statement works as expected. The if statement always runs since playerCont is 3 in this case, so you should remove it. Please let me know if you have any other questions or issues about the whole thing. Thank you!

1 Like

Could you clarify what you are expecting versus what you are getting? You’ve defined four cases and they work as they should. What are you expecting to happen? Thanks!

1 Like

I was expecting that case 3 would be valid for all numbers beyound 2.
However, when i use a number such as 4 or higher the script runs the default case not case 3.

my girlfriend told me that switch cases don’t handle if statement’s or operators as the case itself, like:

case >=2:
//runs code

So what could be the best approach for having a case for 0 players, another for 1, 2 and higher than 2?

Thanks!

There are a couple of ways to approach the issue. You could use a default statement to handle three and above. Another alternative is to use pattern matching. This is beyond the scope of this screencast. I’m not sure if it even works with current versions of Unity.

You essentially write your third case like this:

case int myValue when playerCont >= 3:

Essentially, this populates the variable myValue if playerCount is greater than 3. You then use myValue in your case. You can see this case employs the keyword when.

Keep in mind that this is a more advanced usage of the switch statement. If you are just learning the language, I would just use an if-statement until you get comfortable, then circle back around and evaluate the advanced use cases of the switch.

1 Like

Thank you!

I had understood the usage of cases wrong, but i will keep in mind that i can combine if’s with switch cases. :slight_smile: