switch Statements

switch statements evaluate expressions and match the values of the expressions to case labels. If a match is found, the associated statement executes.

Example—switch statement:

switch (expression){
  case label : 
    statement;
    break;
  case label : 
    statement;
    break;
  ...
  default : statement;
}

The program searches for a label that matches the value of the expression and then executes the associated statement. If no match is found, the program searches for the optional default statement. If a match is found, the program executes the associated statement. If no default statement is found, the program executes at the statement following the end of switch.

Break statements, which are optional, are associated with case labels. Break statements ensure that, after matched statements execute, programs leave switch and continue execution at the statement following switch. If break is omitted, the program continues execution at the next statement of the switch statement.

In the following example, if expr evaluates to Bananas, the program matches the value with case Bananas and executes the associated statement. When break is encountered, the program terminates switch and executes the statement following is.

switch (expr) {
  case "Oranges" : 
    Console.Writeln("Oranges are $0.59 a pound."); 
    break; 
  case "Apples" :
    Console.Writeln("Apples are $0.32 a pound.");
    break;
  case "Bananas" : 
    Console.Writeln("Bananas are $0.48 a pound."); 
    break; 
  case "Cherries" :
    Console.Writeln("Cherries are $3.00 a pound.");
    break; 
  default :
    Console.Writeln("Sorry, we are out of " + i + "."); 
}
Console.Writeln("Is there anything else you'd like?");