;

C# Switch Statement


The switch statement in C# is a powerful control flow mechanism used to select one of many code blocks to be executed, based on the value of a variable or expression. It's often used as an alternative to multiple if-else conditions when there are several possible outcomes. This tutorial will explain the syntax, usage, and examples of the switch statement, explore its benefits, and discuss key takeaways to ensure proper understanding of the concept.

What is a Switch Statement in C#?

The switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is compared to each case in turn. When a match is found, the associated block of code is executed.

It’s particularly useful when you have multiple potential outcomes based on the value of a single expression, making your code cleaner and more readable compared to a series of if-else conditions.

Syntax of the Switch Statement

Here is the basic structure of a switch statement in C#:

switch (expression)
{
    case value1:
        // Code to execute if expression == value1
        break;
    case value2:
        // Code to execute if expression == value2
        break;
    default:
        // Code to execute if none of the cases match
        break;
}

Key Elements:

  • switch (expression): The expression is evaluated once, and its value is compared against the values in the case labels.
  • case value:: If the expression matches value, the associated block of code is executed.
  • break;: Ends the execution of the current case and exits the switch statement. Without break, the code "falls through" to the next case.
  • default:: This block is executed if none of the case values match the expression. It’s similar to an else block in an if-else structure.

How Switch Statement Works

  • The switch statement evaluates the expression once.
  • It then compares the result with each case.
  • If a match is found, the code associated with that case is executed.
  • If no match is found, and a default case is provided, the code inside the default block will run.
  • The break statement ensures that the program doesn’t fall through to subsequent cases.

Example:

int day = 3;

switch (day)
{
    case 1:
        Console.WriteLine("Monday");
        break;
    case 2:
        Console.WriteLine("Tuesday");
        break;
    case 3:
        Console.WriteLine("Wednesday");
        break;
    case 4:
        Console.WriteLine("Thursday");
        break;
    case 5:
        Console.WriteLine("Friday");
        break;
    case 6:
        Console.WriteLine("Saturday");
        break;
    case 7:
        Console.WriteLine("Sunday");
        break;
    default:
        Console.WriteLine("Invalid day");
        break;
}

In this example:

  • The variable day has a value of 3.
  • The switch statement compares the value of day against each case.
  • When it matches case 3, it prints "Wednesday" and exits the switch block.

Examples of Switch Statement Usage

1. Using switch with a Char Type:

char grade = 'B';

switch (grade)
{
    case 'A':
        Console.WriteLine("Excellent!");
        break;
    case 'B':
        Console.WriteLine("Well done!");
        break;
    case 'C':
        Console.WriteLine("Good job");
        break;
    case 'D':
        Console.WriteLine("You passed");
        break;
    case 'F':
        Console.WriteLine("Better luck next time");
        break;
    default:
        Console.WriteLine("Invalid grade");
        break;
}

In this example, the variable grade is compared to a list of possible values (A, B, C, etc.), and the corresponding message is printed.

2. Switch Without break (Fall-Through Behavior):

int number = 2;

switch (number)
{
    case 1:
    case 2:
    case 3:
        Console.WriteLine("Number is between 1 and 3");
        break;
    default:
        Console.WriteLine("Number is outside 1-3 range");
        break;
}

In this case, multiple cases (1, 2, and 3) share the same code block. The absence of break between them causes them to behave similarly.

3. Switch with default Case:

int month = 13;

switch (month)
{
    case 1:
        Console.WriteLine("January");
        break;
    case 2:
        Console.WriteLine("February");
        break;
    default:
        Console.WriteLine("Unknown month");
        break;
}

In this example, since the value of month is 13 (which is not covered by any of the cases), the default block executes, printing "Unknown month".

Pattern Matching with Switch in C#

Since C# 7.0, switch statements support pattern matching, which allows for more advanced comparisons beyond simple values. This feature greatly expands the flexibility of the switch statement.

Example of Pattern Matching:

object obj = 100;

switch (obj)
{
    case int i when i > 50:
        Console.WriteLine($"The number {i} is greater than 50");
        break;
    case int i:
        Console.WriteLine($"The number {i} is 50 or less");
        break;
    default:
        Console.WriteLine("Not a number");
        break;
}

Here, we use pattern matching to not only check if obj is an int, but also apply additional conditions (i > 50). This adds more versatility compared to traditional value-based switch statements.

When to Use Switch vs. if-else

The choice between switch and if-else comes down to readability, simplicity, and use case:

When to Use Switch:

  • When you need to compare one value against multiple possible options.
  • When the number of cases is large (e.g., comparing a variable to many specific values).
  • When using constant values or simple conditions.

When to Use if-else:

  • When the conditions involve complex logical operations or ranges.
  • When comparing multiple variables or expressions.
  • When each condition involves more intricate logic than a simple comparison.

Example: Use if-else for more complex conditions

int age = 25;
if (age > 18 && age < 65)
{
    Console.WriteLine("Working age");
}
else
{
    Console.WriteLine("Not working age");
}

Here, using if-else is better because we’re dealing with a range of values, which is less straightforward with switch.

Common Use Cases for Switch

1. Menu Selection:

When creating console applications or UI-based apps, the switch statement is commonly used to handle user menu selection.

int option = 2;

switch (option)
{
    case 1:
        Console.WriteLine("Start Game");
        break;
    case 2:
        Console.WriteLine("Load Game");
        break;
    case 3:
        Console.WriteLine("Quit");
        break;
    default:
        Console.WriteLine("Invalid option");
        break;
}

2. Handling HTTP Status Codes:

int statusCode = 404;

switch (statusCode)
{
    case 200:
        Console.WriteLine("OK");
        break;
    case 404:
        Console.WriteLine("Not Found");
        break;
    case 500:
        Console.WriteLine("Internal Server Error");
        break;
    default:
        Console.WriteLine("Unknown status code");
        break;
}

In this scenario, the switch statement is an ideal choice for handling HTTP status codes.

Key Takeaways

  • The switch statement is a multi-way branch statement that allows your program to execute one of many code blocks based on the value of an expression.
  • It provides a more readable and concise alternative to multiple if-else statements.
  • Syntax involves switch, case, break, and optionally, default.
  • The default case acts as a fallback when none of the specified cases match.
  • Pattern matching expands the capabilities of the switch statement in newer versions of C#, allowing for more sophisticated comparisons.
  • Use switch when you have a single variable with multiple possible values and if-else when the conditions are more complex.

Summary

The switch statement in C# is a highly useful tool for controlling the flow of your program when working with variables that can have multiple potential values. By understanding its structure and use cases, you can make your code more organized, readable, and efficient.

With the introduction of pattern matching in later versions of C#, the switch statement has become even more versatile, allowing for complex conditional checks in a structured manner. Mastering both switch and if-else gives you the flexibility to handle almost any decision-making logic in your C# programs effectively.