Switch Statements
Switch statements provide an efficient way to select between many options based on a single value.
Basic Switch Statement
csharp1int day = 3;23switch (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:
csharp1// This will not compile without break2switch (value)3{4 case 1:5 Console.WriteLine("One");6 // Error: Control cannot fall through from one case label to another7 case 2:8 Console.WriteLine("Two");9 break;10}
Multiple Cases
Group cases that share the same code:
csharp1char grade = 'B';23switch (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
csharp1string command = "start";23switch (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:
csharp1int day = 3;23string dayName = day switch4{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};1415Console.WriteLine(dayName); // Wednesday
Switch Expression with Multiple Cases
csharp1char grade = 'B';23string message = grade switch4{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
csharp1int score = 85;23string grade = score switch4{5 >= 90 => "A",6 >= 80 => "B",7 >= 70 => "C",8 >= 60 => "D",9 _ => "F"10};
Range Patterns
csharp1int age = 25;23string category = age switch4{5 < 0 => "Invalid",6 < 13 => "Child",7 < 20 => "Teen",8 < 65 => "Adult",9 _ => "Senior"10};
Combined Patterns with and/or
csharp1int month = 7;23string season = month switch4{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:
csharp1int number = 15;23string description = number switch4{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};1112Console.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
csharp1switch (option)2{3 case 1:4 InitializeSystem();5 LoadData();6 Console.WriteLine("Ready");7 break;8 case 2:9 // Multiple statements10 break;11}
Use Expression When:
- Returning or assigning a single value
- Each case maps to one result
- Want concise, readable code
csharp1string result = option switch2{3 1 => "First",4 2 => "Second",5 _ => "Other"6};
Practical Examples
Menu System
csharp1Console.WriteLine("1. New Game");2Console.WriteLine("2. Load Game");3Console.WriteLine("3. Settings");4Console.WriteLine("4. Exit");5Console.Write("Choose: ");67string choice = Console.ReadLine() ?? "";89switch (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
csharp1double a = 10, b = 3;2char operation = '/';34double result = operation switch5{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};1415Console.WriteLine($"{a} {operation} {b} = {result}");
Day Type Checker
csharp1DayOfWeek today = DateTime.Now.DayOfWeek;23string dayType = today switch4{5 DayOfWeek.Saturday or DayOfWeek.Sunday => "Weekend",6 DayOfWeek.Monday => "Start of work week",7 DayOfWeek.Friday => "TGIF!",8 _ => "Weekday"9};1011Console.WriteLine($"{today} is a {dayType}");
Summary
In this lesson, you learned:
- Switch statements select code based on a value
- Each case needs a
breakstatement - 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
whenclauses for additional conditions
Now let's practice with the grade calculator workshop!