This tutorial is about switch statement in C#. Switch statement is used when you have to evaluate a variable for multiple values
Don't forget to check out our site http://howtech.tv/ for more free how-to videos!
http://youtube.com/ithowtovids - our feed
http://www.facebook.com/howtechtv - join us on facebook
https://plus.google.com/103440382717658277879 - our group in Google+
Introduction:
We have seen the if---else construct. Another conditional statement is the switch statement in C#. It is used when you have to evaluate a variable for multiple values.
In C, switch statements are defined by the following syntax:
switch(variablename)
{
case constantexpression_1:
statements;
break;
case constantexpression_2:
statements;
break;
default:
statements;
break;
}
When the switch statement in C# is executed, the variable in the switch statement is evaluated. The value of the variable is 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 match case statement. A break statement is used to exit the switch---case construct. If none of the cases match, the default block gets executed.
The keyword switch is followed by the variable in parentheses. Each case keyword is followed by a possible value for the variable.
The points to be noted here are:
• The data type of the constants should match the data type of the variable being evaluated by the switch construct.
• Before entering the switch construct, a value should be assigned to the switch variable.
• break statement completes a case construct and its compulsory to finish the case.
Step 1: Implementing Switch Statement
A complex if---else construct can be replaced by a simple switch---case construct.
The following code is an example of nested if---else construct:
if (grade==1)
Console.WriteLine("Excellent");
else if (grade==2)
Console.WriteLine("Good");
else if(grade==3)
Console.WriteLine("Fair");
else
Console.WriteLine("Invalid Grade");
This code can be replaced by a switch---case construct as follows:
switch(grade)
{
case 1:
Console.WriteLine("Excellent");
break;
case 2:
Console.WriteLine("Good");
break;
case 3:
Console.WriteLine("Fair");
break;
default:
Console.WriteLine("Invalid Grade");
break;
}
Conclusion
In C, switch statement construct evaluates an expression only once at the top, where as the if---else construct evaluates the expression for each if statement. Thus it can be said that the switch statement in C# is a simpler form of the nested if---else construct.