Control Flow

Switch Case in C#

A switch case is used test variable equality for a list of values, where each value is a case. When the variable is equal to one of the cases, the statements following the case are executed. A break statement ends the switch case. The optional default case is for when the variable does not equal any of the cases.


Syntax
switch(expression) { 
   case valueOne:
      //statements 
      break; 
   case valueTwo: 
      //statements 
      break; 
   default: 
      //optional 
      //statements 
}

Notes

Variable used in a switch statement can only be a short, byte, int or char. The values for each case must be the same data type as the variable type.

When the variable is equal to one of the cases, the statements following the case are executed.

A break statement ends the switch case.

The optional default case is for when the variable does not equal any of the cases.


Example
switch(choice) { 
   case 'Y' : 
      Console.WriteLine("Yes"); 
      break; 
   case 'M' : 
      Console.WriteLine("Maybe"); 
      break; 
   case 'N' : 
      Console.WriteLine("No"); 
      break; 
   default: 
      Console.WriteLine("Invalid response"); 
}

Add to Slack

< If Statement   |   For Loop >

© 2019 SyntaxDB. All Rights Reserved.