12 minlesson

Switch Statements

Switch Statements

Switch statements provide an efficient way to select between many options based on a single value.

Basic Switch Statement

csharp
1int day = 3;
2
3switch (day)
4{
5 case 1:
6 Console.WriteLine("Monday");
7 break;
8 case 2:
9 Console.WriteLine("Tuesday");
10 break;
11 case 3:
12 Console.WriteLine("Wednesday");
13 break;
14 case 4:
15 Console.WriteLine("Thursday");
16 break;
17 case 5:
18 Console.WriteLine("Friday");
19 break;
20 case 6:
21 Console.WriteLine("Saturday");
22 break;
23 case 7:
24 Console.WriteLine("Sunday");
25 break;
26 default:
27 Console.WriteLine("Invalid day");
28 break;
29}

Output

Wednesday

Key Elements

  • switch (expression): The value to match against
  • case value: A possible match
  • break: Exits the switch block (required!)
  • default: Handles unmatched values (optional but recommended)

The break Statement

Unlike some languages, C# requires break (or another jump statement) at the end of each case:

csharp
1// This will not compile without break
2switch (value)
3{
4 case 1:
5 Console.WriteLine("One");
6 // Error: Control cannot fall through from one case label to another
7 case 2:
8 Console.WriteLine("Two");
9 break;
10}

Multiple Cases

Group cases that share the same code:

csharp
1char grade = 'B';
2
3switch (grade)
4{
5 case 'A':
6 case 'B':
7 Console.WriteLine("Great job!");
8 break;
9 case 'C':
10 Console.WriteLine("You passed.");
11 break;
12 case 'D':
13 case 'F':
14 Console.WriteLine("Need improvement.");
15 break;
16 default:
17 Console.WriteLine("Invalid grade.");
18 break;
19}

Switch with Strings

csharp
1string command = "start";
2
3switch (command.ToLower())
4{
5 case "start":
6 Console.WriteLine("Starting...");
7 break;
8 case "stop":
9 Console.WriteLine("Stopping...");
10 break;
11 case "pause":
12 Console.WriteLine("Pausing...");
13 break;
14 case "help":
15 Console.WriteLine("Available commands: start, stop, pause");
16 break;
17 default:
18 Console.WriteLine($"Unknown command: {command}");
19 break;
20}

Switch Expressions (C# 8+)

A more concise syntax for switches that return a value:

csharp
1int day = 3;
2
3string dayName = day switch
4{
5 1 => "Monday",
6 2 => "Tuesday",
7 3 => "Wednesday",
8 4 => "Thursday",
9 5 => "Friday",
10 6 => "Saturday",
11 7 => "Sunday",
12 _ => "Invalid day" // _ is the discard pattern (like default)
13};
14
15Console.WriteLine(dayName); // Wednesday

Switch Expression with Multiple Cases

csharp
1char grade = 'B';
2
3string message = grade switch
4{
5 'A' or 'B' => "Great job!",
6 'C' => "You passed.",
7 'D' or 'F' => "Need improvement.",
8 _ => "Invalid grade."
9};

Pattern Matching in Switch

C# supports powerful pattern matching:

Relational Patterns

csharp
1int score = 85;
2
3string grade = score switch
4{
5 >= 90 => "A",
6 >= 80 => "B",
7 >= 70 => "C",
8 >= 60 => "D",
9 _ => "F"
10};

Range Patterns

csharp
1int age = 25;
2
3string category = age switch
4{
5 < 0 => "Invalid",
6 < 13 => "Child",
7 < 20 => "Teen",
8 < 65 => "Adult",
9 _ => "Senior"
10};

Combined Patterns with and/or

csharp
1int month = 7;
2
3string season = month switch
4{
5 12 or 1 or 2 => "Winter",
6 >= 3 and <= 5 => "Spring",
7 >= 6 and <= 8 => "Summer",
8 >= 9 and <= 11 => "Fall",
9 _ => "Invalid month"
10};

When Clause (Guards)

Add conditions to cases:

csharp
1int number = 15;
2
3string description = number switch
4{
5 0 => "Zero",
6 > 0 when number % 2 == 0 => "Positive even",
7 > 0 => "Positive odd",
8 < 0 when number % 2 == 0 => "Negative even",
9 < 0 => "Negative odd"
10};
11
12Console.WriteLine(description); // Positive odd

Switch Statement vs Expression

Use Statement When:

  • Executing multiple statements per case
  • Performing actions without returning a value
  • Need complex logic in cases
csharp
1switch (option)
2{
3 case 1:
4 InitializeSystem();
5 LoadData();
6 Console.WriteLine("Ready");
7 break;
8 case 2:
9 // Multiple statements
10 break;
11}

Use Expression When:

  • Returning or assigning a single value
  • Each case maps to one result
  • Want concise, readable code
csharp
1string result = option switch
2{
3 1 => "First",
4 2 => "Second",
5 _ => "Other"
6};

Practical Examples

Menu System

csharp
1Console.WriteLine("1. New Game");
2Console.WriteLine("2. Load Game");
3Console.WriteLine("3. Settings");
4Console.WriteLine("4. Exit");
5Console.Write("Choose: ");
6
7string choice = Console.ReadLine() ?? "";
8
9switch (choice)
10{
11 case "1":
12 Console.WriteLine("Starting new game...");
13 break;
14 case "2":
15 Console.WriteLine("Loading saved game...");
16 break;
17 case "3":
18 Console.WriteLine("Opening settings...");
19 break;
20 case "4":
21 Console.WriteLine("Goodbye!");
22 break;
23 default:
24 Console.WriteLine("Invalid option. Please try again.");
25 break;
26}

Calculator Operation

csharp
1double a = 10, b = 3;
2char operation = '/';
3
4double result = operation switch
5{
6 '+' => a + b,
7 '-' => a - b,
8 '*' => a * b,
9 '/' when b != 0 => a / b,
10 '/' => throw new DivideByZeroException(),
11 '%' when b != 0 => a % b,
12 _ => throw new ArgumentException($"Unknown operation: {operation}")
13};
14
15Console.WriteLine($"{a} {operation} {b} = {result}");

Day Type Checker

csharp
1DayOfWeek today = DateTime.Now.DayOfWeek;
2
3string dayType = today switch
4{
5 DayOfWeek.Saturday or DayOfWeek.Sunday => "Weekend",
6 DayOfWeek.Monday => "Start of work week",
7 DayOfWeek.Friday => "TGIF!",
8 _ => "Weekday"
9};
10
11Console.WriteLine($"{today} is a {dayType}");

Summary

In this lesson, you learned:

  • Switch statements select code based on a value
  • Each case needs a break statement
  • Group cases that share the same behavior
  • Switch expressions (C# 8+) are more concise for value mappings
  • Pattern matching enables relational and logical patterns
  • Use when clauses for additional conditions

Now let's practice with the grade calculator workshop!