Switch Statement

The switch statement in C# is a control flow statement that allows you to execute a block of code based on the value of a variable. It is similar to a series of if-else statements but provides a more readable and organized way to handle multiple conditions.

Structure of a switch Statement

The basic structure of a switch statement includes:

  • The switch keyword followed by an expression in parentheses.
  • A series of case labels, each representing a specific value that the expression can take.
  • A default case, which is optional and executes if none of the case values match the expression.

Example

using System;

class Program
{
  static void Main()
  {
      int dayOfWeek = 5;
      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 of the week");
              break;
      }
  }
}

Explanation of the Example

  • The variable dayOfWeek is initialized to the value 5.
  • The switch statement evaluates the value of dayOfWeek.
  • It matches the value with the appropriate case label.
  • When dayOfWeek is 5, the corresponding block of code for case 5 is executed, printing “Friday” to the console.
  • The break statement is used to terminate the switch block and prevent the execution from falling through to subsequent cases.
  • The default case provides a fallback option if none of the case labels match the value of dayOfWeek. In this case, it prints “Invalid day of the week.

Advantages of Using switch

Readability: switch statements are more readable and organized than multiple if-else statements, especially when dealing with multiple conditions.
Performance: In some cases, switch statements can be more efficient than if-else chains, as the compiler may optimize them better.

Limitations in switch statement

  • Switch statements can only evaluate discrete values (such as integers, characters, and strings) and cannot handle ranges or complex conditions.
  • Every case should end with a break, return, or goto statement to prevent fall-through, except when intentionally leveraging fall-through logic.
Post a comment

Leave a Comment

Scroll to Top