Home
Blog
When to Use Switch in C#
Updated
Dot Net Perls

When to Use Switch in C#

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:

Can occasionally be optimized better than an if-else chain, but this probably will only happen in situations with constant integer cases.
May appear more elegant and polished in the code—the code looks like it has been written with more care.
May be slower than an 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.

Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
An RSS feed is available for this blog.
Home
Changes
© 2007-2025 Sam Allen