In this lesson, you will learn about the Switch statement in C#, its usage, and examples to better understand the topic.
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.
switch (expression) { case a: // code block break; case b: // code block break; case c: // code block break; default: // code block break; }
Months of the Year
In the switch statement, it’s possible to evaluate more than one expression at a time if needed.
Example
Vowels and Consonants
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 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#.