Light Mode Image

C# Switch Statement

The switch statement is a control flow statement that allows a variable to be tested for equality against a list of values. It provides a concise way to handle multiple possible conditions.

 

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

switch (variable)
{
    case value1:
        // Code to be executed if variable equals value1
        break;
    case value2:
        // Code to be executed if variable equals value2
        break;
    // additional cases as needed
    default:
        // Code to be executed if variable doesn't match any case
        break;
}

 

Here's a simple example to illustrate how a switch statement works.

using System;

class Program
{
    static void Main()
    {
        int dayOfWeek = 3;

        switch (dayOfWeek)
        {
            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 switch statement checks the value of the dayOfWeek variable and executes the corresponding case block.

 

If dayOfWeek doesn't match any of the specified cases, the code inside the default block will be executed.

 

Remember to use the break statement after each case to exit the switch statement once a match is found. If you omit the break statement, the control will "fall through" to the next case, which may not be the desired behavior.