C# Switch Statement

In this lesson, you will learn about the Switch statement in C#, its usage, and examples to better understand the topic.


What is a Switch Statement?

In the previous lesson, we learned about the ‘if’ statements in C#. The switch statement is similar to the if statement; it executes a code block if a condition is true. However, use the switch statement over the ‘if’ statement if you have too many expressions to evaluate. The switch statement keeps your code cleaner and easier to understand.

Syntax of the switch statement in C#

switch (expression) {
case a:
  // code block
  break;
case b:
  // code block
  break;
case c:
  // code block
  break;
default:
  // code block
  break;
}

Example of the switch statement in C#

Months of the Year

Switch Statement with Grouped cases

In the switch statement, it’s possible to evaluate more than one expression at a time if needed.

Example

Vowels and Consonants

The break Keyword

As you noticed, there is a break keyword in every case in the switch statement. This keyword tells the compiler that there is no need to check other cases when a case returns a ‘true’ value. The compiler will exist the switch statement once the break keyword is reached.


The default case

The compiler will execute the default case and exit the switch statement if no match is found in all cases. In the ‘Months of the year’ example above, the default case will be executed if the user enters anything other than a number between 1 and 12.

This concludes the C# Swith Statement lesson. In the next lesson, you will learn about the Ternary operator in C#.