It is said that the decisions we make determine the lives we live. For developers, we must determine whether to use an if
-statement or switch
. Should developers use switch
more often? And if so, when should switch
be preferred—should we always replace if
-chains with switch
blocks?
Let's consider an if
-else chain that tests for numbers. If all the cases are constant, we can convert the if
-block into a switch
statement. In newer versions of C# we can use ranges and expressions in switch
statements—so even more if
-chains can be converted.
There are some benefits that can be realized by using switch
. The switch
statement:
if
-else chain, but this probably will only happen in situations with constant integer cases.if
-statement if one case occurs frequently, and an if
-statement check for it first.If I am handling a set of char
values, like lowercase letters or punctuation I would prefer a switch
. My thinking is that if there is a complete set of cases we want to consider, and they are all mostly equal in importance, and the cases are simple values like char
or int
, prefer a switch
. Otherwise, reach for the old standby if
-statement.