Switch Statement in C Sharp
by Dinesh[ Edit ] 2012-07-22 21:34:59
The switch Statement in C#
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:
Syntax:
switch (expression)
{
case constant-expression:
statement
jump-statement
[default:
statement
jump-statement]
}
Where:
expression
An integral or string type expression.
statement
The embedded statement(s) to be executed if control is transferred to the case or the default.
jump-statement
A jump statement that transfers control out of the case body.
constant-expression
Control is transferred to a specific case according to the value of this expression.
Remarks:
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.
Example Program:
// 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;
switch(n)
{
case 1:
cost += 25;
break;
case 2:
cost += 25;
goto case 1;
case 3:
cost += 50;
goto case 1;
default:
Console.WriteLine("Invalid selection. Please select 1, 2, or 3.");
break;
}
if (cost != 0)
Console.WriteLine("Please insert {0} cents.", cost);
Console.WriteLine("Thank you for your business.");
}
}
Input : 2
Sample Output:
Coffee sizes: 1=Small 2=Medium 3=Large
Please enter your selection: 2
Please insert 50 cents.
Thank you for your business.