Switch Statements

Lesson 17
Author : Afrixi
Last Updated : February, 2023
C# - Programming Language
This course covers the basics of programming in C#.

In C#, the switch statement is used to execute different blocks of code depending on the value of a given expression. It’s a powerful control structure that can simplify code and make it more readable.

The syntax for a switch statement in C# is as follows:

switch (expression)
{
    case value1:
        // code to be executed if expression matches value1
        break;
    case value2:
        // code to be executed if expression matches value2
        break;
    ...
    default:
        // code to be executed if expression doesn't match any of the above values
        break;
}

The expression is evaluated once, and then the code inside the switch statement is executed based on the value of the expression. If the value of the expression matches one of the cases, the corresponding code block is executed. If none of the cases match the expression, the code inside the default block is executed.

Here’s an example of a switch statement that checks the value of a variable and executes different code blocks depending on its value:

int dayOfWeek = 2;

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

In this example, we’re using a switch statement to check the value of the dayOfWeek variable. Depending on its value, we print out a different message to the console. If dayOfWeek is not a valid day of the week (i.e., not between 1 and 7), we print out an “Invalid day of the week” message using the default block.

Switch statements can also be used with different data types, such as strings, chars, and enums.