+ 7
What is the difference between if else statement and switch statement?
Also, please give an example. They look the same to me but I wanna ask because I am unsure of their usage. Thank you!
10 Réponses
+ 15
With if statements, you can easily test for complex conditions with multiple variables etc. With switch statements you generally test for distinct values or ranges of a single variable.
+ 16
In the case of SWITCH statements, my own description of its value is a control flow pattern for different behaviors based on the various possible values of a single variable.
While the same can be accomplished using IF statements, it's not as clean nor as controlled as using the SWITCH statement.
Here are some pseudo code examples for comparison:
----
if(selected_color == "red")
...
else if(selected_color == "green")
...
else if(selected_color == "blue")
...
else if(selected_color == "black"
or selected_color == "white"
or selected_color == "yellow"
or selected_color == "brown"
or selected_color == "grey")
...
else
... Do this for all other colors.
----
Compared To:
----
switch (selected_color):
case "red":
...
case "green":
...
case "blue":
...
case "black":
case "white":
case "yellow":
case "brown":
case "grey":
...
default:
... Do this for all other colors.
----
I hope this comparison makes sense. 😉👌
+ 10
They are similar in some ways and I would say it's possible to create a type of switch case using if else statements but practicing will help you understand them better
+ 8
Fhatuwani Makhado Sure... nested switch statements is supported. But I never do that. Something like that should be handled in a separate function / method.
+ 7
Ipang You mean something like this? 😮🤓
https://code.sololearn.com/cmY4mx5oPV6z/
+ 5
Short circuit evaluation is only available with `if` statement but not `switch`. If you think you can benefit from this evaluation trick then the `if` statement is your choice.
https://en.m.wikipedia.org/wiki/Short-circuit_evaluation
+ 4
If-statements can be nested (i.e you can have an if-statement inside an if-statement). Can switch be nested?
+ 4
David Carroll
Cool 👍 but I guess we both know that feature is exclusive to some languages.
Isn't the `when` thingy new in C#? I didn't recall it was available when I used it a long time ago. And I am not sure if it implements the short circuit evaluation, need further exploration to confirm 😁
+ 3
Ipang It is relatively new, as of C# 7.0.