Saturday, October 9, 2010

Understanding the Switch… case construct in C sharp.

Switch…case construct is used when there are multiple value for a variable. The switch expression must be of an integer type, such as char, byte, short, or int, or of type string .The default statement sequence is executed if no case constant matches the expression. The default is optional. If default is not present, no action takes place if all matches fail. When a match is found, the statements associated with that case are executed until the break is encountered.

The syntax of the Switch…case construct.

switch(expression)
{
case constant1:
statement sequence
break;
case constant2:
statement sequence
break;
case constant3:
statement sequence
break;
.
.
.
default:
statement sequence
break;

Note: - When the switch statement is executed, the expression given in the switch statement is evaluated and compared with each case constant. If one of the case constants is equal to the value of the variable given in the Switch statement, control is passed to the statement following the matched case label. A break statement is used to exit the switch statement. This prevents the execution of the remaining case structures by ending the execution of the switch..case construct. Each break statement terminates the enclosing switch statement and the flow of control. If none of the case match, the default case is invoked.

Example:

using System;
class SwitchTest
{
public static void Main()
{
Console.WriteLine("Select Best Language: 1= C 2= Php 3=C#");
Console.Write("Please enter your selection: ");
string s = Console.ReadLine();
int n = int.Parse(s);
switch(n)
{
case 0:
case 1:
Console.WriteLine("Not Bad, Try Again");
break;
case 2:
Console.WriteLine("Not Even Close");
break;
case 3:
Console.WriteLine("You’re Right, Congradulations");
break;
default:
Console.WriteLine("Invalid selection. Please select 1, 2, or 3.");
break;
}
}
}

Sample Output
is show below:



C Sharp Statements Related Contents.

Understanding the while Loop constructs in C sharp.
Understanding the for loop in c sharp.
if...else construct in c sharp.
How to use do…while loop in C #.

No comments:

Recent Posts