What is the benefit/downside to using a switch
statement vs. an if/else
in C#. I can\'t imagine there being that big of a difference, other than m
Three reasons to prefer the switch
:
A compiler targeting native code can often compile a switch statement into one conditional branch plus an indirect jump whereas a sequence of if
s requires a sequence of conditional branches. Depending on the density of cases a great many learned papers have been written about how to compile case statements efficiently; some are linked from the lcc compiler page. (Lcc had one of the more innovative compilers for switches.)
A switch statement is a choice among mutually exclusive alternatives and the switch syntax makes this control flow more transparent to the programmer then a nest of if-then-else statements.
In some languages, including definitely ML and Haskell, the compiler checks to see if you have left out any cases. I view this feature as one of the major advantages of ML and Haskell. I don't know if C# can do this.
An anecdote: at a lecture he gave on receiving an award for lifetime achievement, I heard Tony Hoare say that of all the things he did in his career, there were three that he was most proud of:
case
statement)I can't imagine living without switch
.