Nerd For Tech
Published in

Nerd For Tech

Switch statements — the ‘clean’ If/Else If statements in C#

When trying to trigger certain code based on the contents of a certain variable in C#, an If/Else If statement is a quick and easy way to achieve this — as demonstrated in my last article

A simple If/Else If statement

However, as the potential options increase, the code can quickly become difficult and confusing to read. Requiring us to add a whole new condition comparison for each new item, for example —

Still not too bad as it is, but consider what this would start to look like with 20 or 50 or 100 different options, with several lines of code in each block…ugh!

Luckily, C# gives us a nice clean way to filter through the contents of our variable in a nice, clean, readable manner.

The switch statement —

Ahh…. switch!

The above 2 snippets of code both accomplish the exact same results but the switch statement above is far cleaner and more readable.

A switch statement can be used for any direct comparisons with any variable type, for example —

Switch statement for Strings

The syntax is quite simple to get use to with the variable you want to filter through stated in parenthesis

switch (varName) {cases}

Followed by a code block containing all ‘cases’ for comparison.

case [condition]:

Each case requires an ‘exit’ from the switch statement as only a single case will be run with each iteration through the switch.

break;

Any code you want to run based on that case condition is placed after the semi-colon and before the break.

A final optional default case is available, should you have need to catch everything and run default code or just notify in case of error.

case default:

or simply

default:

The default case also needs to be followed by a break.

While this does make code much easier to read, I will mention it does have some limitations when compared to If statements —

You cannot compare multiple variables in a single switch statement,

You cannot compare to multiple conditions or a range of values,

You can ONLY compare directly — i.e. does that EQUAL this,

You can, however, use the default case to catch everything that doesn’t meet the specific criteria — the same as using an Else at the end of an If/Else If statement.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Les Street

Les Street

27 Followers

A UK based Unity Developer with a passion for gaming and coding