If vs. switch

Personally, I have always preferred switch over if’s if I have 2 or 3 choices to make. I started using them in VB which has a simpler format. They look cleaner than a bunch of if else if’s. :slight_smile:

6 Likes

Even though switch case is cleaner and faster than if- else. I just prefer if- else because it’s more “English” to me if that makes sense XD

2 Likes

I totally agree @Ron_Welch

I know what you mean

id never heard of switch before today but now I’m going to use them every single time

On thing I haven’t seen mentioned is the use of switch statements with enum types.

On VS, declare an enum:

enum Screen { MainMenu, Password, Win }

Declare a variable of that enum type:

Screen currentScreen;

Then type switch [tab] [tab] to use the switch code snippet, fill in your variable of type enum, and press enter. It will automatically create case statements for each enum type:

    switch (currentScreen)
    {
        case Screen.MainMenu:
            break;
        case Screen.Password:
            break;
        case Screen.Win:
            break;
        default:
            break;
    }

This can save you a lot of time and ensure that you don’t forget to handle one of your enums!

2 Likes

I agree that if statements seem more “English” but I do like the functionality of the switch and will try to integrate it effectively in the future!

Interesting. I like it when the IDE does the work for us. Not sure how this would be used at this time but I am sure that we will get to it later in the course! Nice tidbit to tuck away in the brainpan.

1 Like

It comes in handy anytime you’re working with objects that are mutually exclusive. For example, you can only be running OR sitting OR standing at any given time. If you define all those as enums for player state purposes, then when you need to work with them you can use that switch snippet to easily generate the base decision structure.

I think that switch is a lot easier to work with than if-else when you are checking more than three things.

Yeah switch statements are a lot easier to structure, but I find if statements are a lot more versatile. Which I think is translated by how tricky they can be to use sometimes.

As soon as the expressions in your if statements start getting complex, switch is a godsend. It helps simplify a lot and keeps things in relative order. I understand the appeal of using if-else but honestly its just personal preference, with one being more convenient in certain situations than the other.

I just learned about switch statement and i feel it can be useful to prevent a lot of repititive if statements but if statements make more sense to me at the moment :slight_smile:

Privacy & Terms