Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All


The switch statement is a control statement that handles multiple selections by passing control to one of the case statements within its body. It takes the following form:

switch (expression)
   case constant-expression:


An integral or string type expression.
The embedded statement(s) to be executed if control is transferred to the case or the default.
A jump statement that transfers control out of the case body.
Control is transferred to a specific case according to the value of this expression.


Control is transferred to the case statement whose constant-expression matches expression. The switch statement can include any number of case instances, but no two case constants within the same switch statement can have the same value. Execution of the statement body begins at the selected statement and proceeds until the jump-statement transfers control out of the case body.

Notice that the jump-statement is required after each block, including the last block whether it is a case statement or a default statement. Unlike the C++ switch statement, C# does not support an explicit fall through from one case label to another. If you want, you can use goto a switch-case, or goto default.

If expression does not match any constant-expression, control is transferred to the statement(s) that follow the optional default label. If there is no default label, control is transferred outside the switch.


// statements_switch.cs
using System;
class SwitchTest 
   public static void Main()  
      Console.WriteLine("Coffee sizes: 1=Small 2=Medium 3=Large"); 
      Console.Write("Please enter your selection: "); 
      string s = Console.ReadLine(); 
      int n = int.Parse(s);
      int cost = 0;
         case 1:   
            cost += 25;
         case 2:            
            cost += 25;
            goto case 1;           
         case 3:            
            cost += 50;
            goto case 1;         
            Console.WriteLine("Invalid selection. Please select 1, 2, or 3.");            
       if (cost != 0)
          Console.WriteLine("Please insert {0} cents.", cost);
       Console.WriteLine("Thank you for your business.");



Sample Output

Coffee sizes: 1=Small 2=Medium 3=Large
Please enter your selection: 2
Please insert 50 cents.
Thank you for your business.

Code Discussion

  • In the preceding example, an integral type variable, n, was used for the switch cases. Notice that you can also use the string variable, s, directly. In this case, you can use switch cases like these:
       case "1":
       case "2":
  • Although fall through from one case label to another is not supported, it is allowed to stack case labels, for example:
       case 0:
       case 1:
          // do something; 

See Also

C# Keywords | Compare to C++ | if | C. Grammar

© 2015 Microsoft