Ad space (banner)
#๏ธโƒฃC# Lessons
Lesson 14 / 68

The switch Statement

In this lesson you will learn how to branch on several values with a switch statement in C#, which reads more clearly than a chain of if statements. This is for anyone searching for "C# switch statement how to use".

A switch statement is a tidier way to branch on a single value than lining up if / else if clauses. Do not forget the break.

The sample code prints a different message for case 1 through case 3 depending on day, and falls back to "Other day" in default. Requiring a break at the end of each case is characteristic of C#.

A common stumbling block for beginners is leaving out break. In C-family languages, omitting it makes execution continue into the next case (fall-through), so every case needs one at the end.

In real-world development, this is a frequently used construct that keeps branches with many options readable. Newer versions of C# also add a switch expression, which is even more concise.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run C# directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)