C# Language Switch statements


Example

A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.

A switch statement is often more concise and understandable than if...else if... else.. statements when testing multiple possible values for a single variable.

Syntax is as follows

switch(expression) {
   case constant-expression:
      statement(s);
      break;
   case constant-expression:
      statement(s);
      break;
  
   // you can have any number of case statements
   default : // Optional
      statement(s);
      break;
}

there are sevaral things that have to consider while using the switch statement

  • The expression used in a switch statement must have an integral or enumerated type, or be of a class type in which the class has a single conversion function to an integral or enumerated type.
  • You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon. The values to compare to have to be unique within each switch statement.
  • A switch statement can have an optional default case. The default case can be used for performing a task when none of the cases is true.
  • Each case has to end with a break statement unless it is an empty statement. In that case execution will continue at the case below it. The break statement can also be omitted when a return, throw or goto case statement is used.

Example can be given with the grades wise

char grade = 'B';

switch (grade)
{
    case 'A':
        Console.WriteLine("Excellent!");
        break;
    case 'B':
    case 'C':
        Console.WriteLine("Well done");
        break;
    case 'D':
        Console.WriteLine("You passed");
        break;
    case 'F':
        Console.WriteLine("Better try again");
        break;
    default:
        Console.WriteLine("Invalid grade");
        break;
}