C# switch Statement

The switch statement in C# is a control flow statement that executes one out of many possible code blocks based on the value of an expression. It is an alternative to using multiple if-else if statements when you need to compare a single value against multiple possible values.

Syntax:


switch (expression)
{
    case value1:
        // Executes this block if expression equals value1
        break;
    
    case value2:
        // Executes this block if expression equals value2
        break;
    
    // Additional cases can be added
    default:
        // Executes if none of the cases match
        break;
}

Expression:

  • expression: This is the value or variable that you want to test.
  • case value: Each case represents a potential match. If the expression matches the value, the corresponding block of code is executed.
  • break: After executing a case, the break statement is used to exit the switch block. If you omit the break, the code will “fall through” to the next case (which is not allowed in C#).
  • default: This is an optional block that executes if none of the case values match the expression.

Example 1:


using System;

class MyExample
{
    static void Main()
    {
        int day = 2;

        switch (day)
        {
            case 1:
                Console.WriteLine("Monday");
                break;
            case 2:
                Console.WriteLine("Tuesday");
                break;
            case 3:
                Console.WriteLine("Wednesday");
                break;
          
            default:
                Console.WriteLine("Invalid day");
                break;
        }
    }
}

Output:

Tuesday

Example2:


using System;

enum Day { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }

class ProgramExample
{
    static void Main()
    {
        Day today = Day.Friday;

        switch (today)
        {
            case Day.Monday:
                Console.WriteLine("Start of the work week!");
                break;
            case Day.Friday:
                Console.WriteLine("End of the work week!");
                break;
            default:
                Console.WriteLine("It's a regular day.");
                break;
        }
    }
}

Output:

End of the work week!