The switch statement is a control statement that handles multiple selections by passing control to one of the case statements within its body. The switch statement takes the form:
switch (expression) { case constant-expression: statement jump-statement [default: statement] }
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. Only the last block does not require a jump-statement whether this block is a case, 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.
using System; using System.IO; 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); switch(n) { case 0: goto case 1; case 1: Console.WriteLine("You selected small size. Insert 50 cents."); break; case 2: Console.WriteLine("You selected medium size. Insert 75 cents."); break; case 3: Console.WriteLine("You selected large size. Insert $1.00."); break; default: Console.WriteLine("Invalid selection. Please select 1, 2, or 3."); } Console.WriteLine("Thank you for your business."); } }
Coffee sizes: 1=Small 2=Medium 3=Large Please enter your selection: 2 You selected medium size. Insert 75 cents. Thank you for your business.
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:
switch(s) { case "1": ... case "2": ... }
C# Keywords | Compare to C++ | if | Grammar