I usually use the switch statement when I have to write multiple condition statements, often where there are three or more well-defined conditions.
However, to handle a biconditional statement including a fall-through behavior, I am often hesitating between a simple if, else if, else statement and the switch statement :
if (condition1)
{
// handling condition1.
}
else if (condition2)
{
// handling condition2.
}
else
{
// handling fall-through.
}
or
switch (n)
{
case condition1:
// handling condition1.
break;
case condition2:
// handling condition2.
break;
default:
// handling fall-through.
break;
}
The Wikipedia Switch statement article states :
In some languages and
programming environments, the use of a case or switch statement is
considered superior to an equivalent series of if-else statements
because it is:
- easier to debug (e.g. setting breakpoints on code vs. a call table, if the debugger has no conditional breakpoint capability)
- easier to read (subjective)
- easier to understand and therefore
- easier to maintain
- faster execution potential
About the .NET Common Language Runtime, is faster execution potential of a switch statement be realistic in this case ?
I am curious to know how the Common Language Runtime is handling both scenarios and how one would be preferable over the other.
Faster execution potential means it tries to use binary search if possible (instead of linear search, in the
if... else if...case).However,
if... else if...is generally more powerful, as it can do things thatswitchcannot do.So I guess if all you need to do is to compare a string or an integer, use
switch. It also help a little with readability.