c sharp Logo

C# Switch


Switch Statements

The switch statement is a control flow structure in C# used to execute different code blocks based on the value of an expression. It is an alternative to using multiple nested if-else statements when dealing with multiple possible values.

Syntax

The syntax of a switch statement is as follows:

switch (expression) {

  case value1:

    // Code block to execute if expression equals value1

    break;

  case value2:

    // Code block to execute if expression equals value2

    break;

  // ... more cases

  default:

    // Code block to execute if no case matches

    break;

}

 

Example

Consider the following code that checks the day of the week:

int day = 3;

 

switch (day) {

  case

 1:

    Console.WriteLine("Monday");

    break;

  case

 2:

    Console.WriteLine("Tuesday");

    break;

  case

 3:

    Console.WriteLine("Wednesday");

    break;

  // ... more cases

  default:

    Console.WriteLine("Invalid day");

    break;

}

 

In this example, the switch statement evaluates the day variable and executes the corresponding case block based on its value. The break keyword ensures that only the code block for the matching case is executed. The default case is used if none of the case values match.

Benefits of Using Switch Statements

  • Improved code readability and maintainability compared to nested if-else statements.
  • Clearer representation of multiple possible values and their corresponding actions.
  • Reduced code duplication and nesting.

Conclusion

The switch statement is a powerful control flow tool in C# that allows for efficient and structured decision-making based on multiple possible values. It promotes code readability and organization when dealing with multiple cases, making it a valuable tool for C# programmers.