Introduction
we looked at basic if-statements and decision-making. Before moving on to the next real topic, we want to take a moment and discuss a construct in C# that is very similar to if statements. These statements are called switch statements. We’ll take a look at when we’d want to use switch statements, how to do them, and then wrap up with a couple of extra details about switch statements.
The basics of switch statements
It is pretty common to have a variable and want to do something different depending on the value of that variable, For instance. It’s say we have a menu with five choices (1-5), and the user types in their choice, which we store in a variable. We want to do something different. depending on which value they chose.
we’d probably think about a sophisticated if/else-if statement using what we already know. or rather an if/ else if/ else
int menuChoice = 3;
if (menuChoice == 1)
{
Console.WriteLine("You chose option #1.");
}
else if (menuChoice == 2)
{
Console.WriteLine("You chose option #2. I like that one too!");
}
else if (menuChoice == 3)
{
Console.WriteLine("I can't believe you chose option #3.");
}
else if (menuChoice == 4)
{
Console.WriteLine("You can do better than 4....");
}
else if (menuChoice == 5)
{
Console.WriteLine("5? Really? That's what you went with?");
}
else
{
Console.WriteLine("Hey! That wasn't even an option!");
}
The Problem: “if-else fatigue”
while the if/elseif structure is logically sound, it can become difficult to read and maintain as your menu grows.
- Repetitive You have to type
menuchoice ==every single time. - Cluttered The logic is buried under repetitive syntax.
- Efficiency: For a long list of choices, a
switchis often slightly more efficient for the compiler to process.
The Solution: The Switch Statement
A switch statement acts like a “lookup table”. You tell the computer which variable to look at, and it jumps straight to the “case” that matches.
Syntax
switch (variableToCheck)
{
case value1:
// Code to run if variableToCheck == value1
break;
case value2:
// Code to run if variableToCheck == value2
break;
default:
// Code to run if NO cases match (The "Else")
break;
}
int menuChoice = 3;
switch (menuChoice)
{
case 1:
Console.WriteLine("You chose option #1");
break;
case 2:
Console.WriteLine("You chose option #2. I like that one too!");
break;
case 3:
Console.WriteLine("I can't believe you chose option #3.");
break;
case 4:
Console.WriteLine("You can do better than 4....");
break;
case 5:
Console.WriteLine("5? Really? That's what you went with?");
break;
default:
Console.WriteLine("Hey! That wasn't even an option!");
break;
}
The must-known” rules
to use a switch statement correctly, you need to remember these three components:
1. The case label
Each case represents a possible value.
- Unlike an
ifstatement, you don’t need parentheses or curly braces for every individual case. - You just use a colon (
:) to start the block of code for that value.
2. The break keyword
This is the most important part!
- Without a
breakthe computer doesn’t know when to stop, In many languages (like C#) it will actually throw an error if you forget it. - It “breaks” you out of the curly braces so the program can continue below the switch.
3. The default case
Think of this as your safety net.
- If the user enters
99but your menu only goes from1-5, thedefaultblock will catch it - It is essentially the
elseat the end of anif/elsechain.
No Implicit Fall-Through
If you are coming from the C++ or Java world into the C# world, you may be aware of a little trick that you can do, where one case block “falls through” to the next block if you leave off the break statement.
// This doesn't work in C#
switch (menuChoice)
{
case 1:
Console.WriteLine("You chose 1.");
case 2:
Console.WriteLine("You chose 2. Or maybe you chose 1.");
break;
}
Because there’s no break, in case 1, the code there would be executed and then continue on down into the case 2 block until you hit a break statement. This isn’t allowed in C#. Every case block needs a break statement.
The reason for requiring this is that people accidentally ended up doing this far more often than they intentionally used it. They leave off the break statement by accident, resulting in a bug that is usually somewhat tricky to resolve. To prevent this, C# won’t even allow you to leave off the break statement and fall through.
However, there is one situation where you can do this. That situation is if you have multiple case blocks with no code in between it:
// This does work in C#
switch (menuChoice)
{
case 1:
case 2:
Console.WriteLine("You chose option 1 or 2.");
break;
This allows you to do the same thing, regardless of whether the value is 1 or 2. And in this case, while case 1 doesn’t have a break statement, it also doesn’t need it because we’re simply saying “cases 1 and 2 are the same thing.”
This could be thought of as basically something like “if [something] or [something else], then do [something cool]”. You can write the same thing with an if statement as well.
Switch Expressions
Switch expressions are a more modern, streamlined way to handle logic in C#. While the Switch Statement is a set of commands to execute, the Switch Expression is a formula used to calculate a value.
1. Structural Comparison Notice how much “syntax noise” is removed when moving from a statement to an expression
| Feature | Switch Statement | Switch Expression |
|---|---|---|
| Primary Goal | Perform tasks (Commands) | Map/Return a value (Calculation) |
| Variable Order | switch (variable) | variable switch |
| Matching | case X: | X => |
| Separators | break; or return; | , (Comma-separated) |
| Default | default: | _ (The Discard) |
2. The Syntax
int number = word switch
{
"zero" => 0, // If word is "zero", return 0
"one" => 1, // If word is "one", return 1
"two" => 2, // If word is "two", return 2
_ => -1 // The "Discard" (Default case)
};
-
The Lambda Arrow (
=>): Read this as “results in.” For example: “The case ‘zero’ results in the value 0.” -
The Discard (
_): This is mandatory if your cases don’t cover every possible input. It handles everything else. -
Semicolon Position: Note that the semicolon (
;) goes at the very end of the curly braces, because the entire switch block is technically one single assignment statement.
Console.Write("Type a number word like 'four': ");
string word = Console.ReadLine();
int number;
number = word switch
{
"zero" => 0,
"one" => 1,
"two" => 2,
"three" => 3,
"four" => 4,
"five" => 5,
"ten" => 10,
"one hundred" => 100,
_ => -1
};
if (number == -1)
{
Console.WriteLine("I did not understand that.");
}
else
{
Console.WriteLine("I recognized that. It was the number " + number + "!");
}