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.
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.
Switch StatementHere 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;
}
switch (expression): The expression is evaluated once, and its value is compared against the values in the case labels.switch statement. Without break, the code "falls through" to the next case.if-else structure.Switch Statement Worksswitch statement evaluates the expression once.default case is provided, the code inside the default block will run.break statement ensures that the program doesn’t fall through to subsequent cases.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:
day has a value of 3.switch statement compares the value of day against each case.Wednesday" and exits the switch block.Switch Statement Usageswitch 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.
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.
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".
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.
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.
Switch vs. if-elseThe choice between switch and if-else comes down to readability, simplicity, and use case:
Switch:if-else:if-else for more complex conditionsint 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.
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;
}
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.
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.if-else statements.switch, case, break, and optionally, default.switch statement in newer versions of C#, allowing for more sophisticated comparisons.switch when you have a single variable with multiple possible values and if-else when the conditions are more complex.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.