Mastering C# `switch` Statements: Efficient Conditional Logic

Learn how to use C#'s `switch` statement for efficient conditional logic. This tutorial explains its syntax, the importance of the `break` statement, and how to use the `default` case, providing a concise alternative to lengthy `if-else if` chains for improved code readability and maintainability.



Understanding C# `switch` Statements

The C# `switch` statement provides a way to select one block of code to execute from multiple possible blocks based on the value of an expression. It's a more concise alternative to a chain of `if-else if` statements when you have multiple conditions to check.

`switch` Statement Syntax


switch (expression) {
    case value1:
        // Code to execute if expression == value1
        break;
    case value2:
        // Code to execute if expression == value2
        break;
    // ... more cases ...
    default:
        // Code to execute if no case matches
        break;
}

The `expression` is evaluated, and the code block associated with the matching `case` is executed. The `break` statement is crucial; it prevents the code from "falling through" to the next case. The `default` case is optional and executes if no other case matches.

Example: A Simple `switch` Statement


using System;

public class SwitchExample {
    public static void Main(string[] args) {
        Console.WriteLine("Enter a number:");
        int num = Convert.ToInt32(Console.ReadLine());
        switch (num) {
            case 10: Console.WriteLine("It's 10"); break;
            case 20: Console.WriteLine("It's 20"); break;
            case 30: Console.WriteLine("It's 30"); break;
            default: Console.WriteLine("Not 10, 20, or 30"); break;
        }
    }
}

Important Note

In C#, the `break` statement is mandatory within each `case` block of a `switch` statement. Without `break`, the code would continue executing through subsequent cases until a `break` is encountered or the end of the `switch` is reached (fallthrough).