Skip to main content

C# Switch Case

Introduction

The switch statement in C# provides a cleaner, more readable alternative to multiple if-else statements when checking a single variable against multiple possible values. It's particularly useful when you need to execute different code blocks based on the value of a single expression.

Unlike multiple if-else statements, a switch statement can be more efficient and easier to read, especially when dealing with many possible conditions based on a single variable.

Basic Syntax

Here's the basic syntax of a C# switch statement:

csharp
switch (expression)
{
case value1:
// Code to execute if expression equals value1
break;
case value2:
// Code to execute if expression equals value2
break;
// More case statements as needed
default:
// Code to execute if expression doesn't match any case
break;
}

Let's explore each component:

  • expression: The variable or expression being evaluated
  • case value: A constant value to compare against the expression
  • break: Terminates the switch block (required at the end of each case)
  • default: Optional case that executes when no other cases match

Simple Example

Let's start with a basic example that determines the name of a day based on a number:

csharp
int dayNumber = 3;
string dayName;

switch (dayNumber)
{
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day number";
break;
}

Console.WriteLine($"Day {dayNumber} is {dayName}");

Output:

Day 3 is Wednesday

The break Keyword

Each case section must end with a break statement (or another jump statement like return or goto). The break statement prevents "falling through" to the next case, which would execute the code in the next case regardless of whether that case's condition was met.

If you forget to include a break, the compiler will generate an error.

The default Case

The default case is optional and handles situations where the expression doesn't match any of the defined cases. It's similar to the else clause in an if-else statement chain.

csharp
char grade = 'X';
string message;

switch (grade)
{
case 'A':
message = "Excellent!";
break;
case 'B':
message = "Good job!";
break;
case 'C':
message = "Satisfactory";
break;
case 'D':
message = "Passed";
break;
case 'F':
message = "Failed";
break;
default:
message = "Invalid grade";
break;
}

Console.WriteLine(message);

Output:

Invalid grade

Multiple Case Labels

You can have multiple case labels for the same code block when you want the same action for different values:

csharp
char choice = 'Y';
bool continueProgram;

switch (choice)
{
case 'Y':
case 'y':
continueProgram = true;
break;
case 'N':
case 'n':
continueProgram = false;
break;
default:
Console.WriteLine("Invalid choice. Defaulting to No.");
continueProgram = false;
break;
}

Console.WriteLine($"Continue program: {continueProgram}");

Output:

Continue program: True

Switch Expressions (C# 8.0+)

C# 8.0 introduced an enhanced form called "switch expressions" that is more concise for simple cases:

csharp
int dayNumber = 3;
string dayName = dayNumber switch
{
1 => "Monday",
2 => "Tuesday",
3 => "Wednesday",
4 => "Thursday",
5 => "Friday",
6 => "Saturday",
7 => "Sunday",
_ => "Invalid day number"
};

Console.WriteLine($"Day {dayNumber} is {dayName}");

Output:

Day 3 is Wednesday

Note that:

  • The syntax uses => instead of colons and break statements
  • The _ (underscore) replaces the default keyword
  • The entire switch is an expression that returns a value

Pattern Matching in Switch Statements

C# 7.0 and later versions allow you to use patterns in switch statements, enhancing their power:

Type Patterns

csharp
object item = "Hello";

switch (item)
{
case int i:
Console.WriteLine($"Item is an integer with value {i}");
break;
case string s:
Console.WriteLine($"Item is a string with value \"{s}\"");
break;
case bool b:
Console.WriteLine($"Item is a boolean with value {b}");
break;
case null:
Console.WriteLine("Item is null");
break;
default:
Console.WriteLine($"Item is of type {item.GetType()}");
break;
}

Output:

Item is a string with value "Hello"

When Clauses

You can add when clauses to case statements to add additional conditions:

csharp
int score = 85;

switch (score)
{
case int n when n >= 90:
Console.WriteLine("Grade: A");
break;
case int n when n >= 80:
Console.WriteLine("Grade: B");
break;
case int n when n >= 70:
Console.WriteLine("Grade: C");
break;
case int n when n >= 60:
Console.WriteLine("Grade: D");
break;
default:
Console.WriteLine("Grade: F");
break;
}

Output:

Grade: B

Real-World Application: Simple Calculator

Let's implement a simple calculator using a switch statement:

csharp
double a = 10;
double b = 5;
char operation = '+';
double result = 0;

switch (operation)
{
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
if (b != 0)
result = a / b;
else
{
Console.WriteLine("Error: Division by zero");
return;
}
break;
default:
Console.WriteLine("Error: Invalid operation");
return;
}

Console.WriteLine($"{a} {operation} {b} = {result}");

Output:

10 + 5 = 15

Real-World Application: Menu System

Here's how you might use a switch statement to build a simple menu system:

csharp
Console.WriteLine("Simple Menu System");
Console.WriteLine("1. View Profile");
Console.WriteLine("2. Edit Settings");
Console.WriteLine("3. Help");
Console.WriteLine("4. Exit");
Console.Write("Enter your choice (1-4): ");

int choice = int.Parse(Console.ReadLine());

switch (choice)
{
case 1:
Console.WriteLine("Loading profile...");
// Code to load profile would go here
break;
case 2:
Console.WriteLine("Opening settings...");
// Code to open settings would go here
break;
case 3:
Console.WriteLine("Displaying help...");
// Code to display help would go here
break;
case 4:
Console.WriteLine("Exiting program...");
// Code to exit would go here
break;
default:
Console.WriteLine("Invalid choice. Please select a number between 1 and 4.");
break;
}

When to Use Switch vs. If-Else

Use a switch statement when:

  • Testing a single variable against multiple known values
  • You have many possible execution paths based on one variable
  • You want more readable code with many conditions

Use if-else statements when:

  • Testing multiple different variables
  • Using complex conditions that can't easily be represented as constant cases
  • You only have a few conditions to check

Common Mistakes and Best Practices

  1. Forgetting break statements: Always include break (or another jump statement) at the end of each case.

  2. Order matters in pattern matching: More specific cases should come before general ones, especially when using when clauses.

  3. Switch expressions vs. statements: Use switch expressions for simple value assignments; use switch statements for more complex logic.

  4. Default case: It's a good practice to include a default case to handle unexpected values.

  5. Readability: Keep case statements short. Consider extracting complex logic into separate methods.

Summary

The switch statement in C# provides a powerful and readable way to handle multiple branching paths based on a single value. It offers several advantages over multiple if-else statements, including improved readability and potential performance benefits.

C# has enhanced the switch statement with pattern matching, switch expressions, and when clauses, making it even more useful in modern programming.

Exercises

  1. Create a program that converts numeric month values (1-12) to month names.

  2. Write a switch statement that categorizes characters as vowels, consonants, digits, or special characters.

  3. Create a simple role-based menu system where different options are presented depending on whether the user is an "admin", "manager", or "user".

  4. Convert a series of if-else statements to a switch statement, and vice versa.

Additional Resources



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)