Switch Statement:
The switch statement, also known as Multiple-choice statements allow our program to choose from several alternatives. A switch Statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on its for each case.
As shown in above figure, the "Switch Expression" is an Expression that produce an case integral or enumerated type. The Switch compares the result of "Switch Expression" to each integral value of case. if it finds a match, the corresponding statement of that case will executes. if it did not find a match on first case, then switch will try next and so on. if no match occurs, the default statement executes.
Did you Notice in the picture the every case end with a Break which causes execution to jump to the end of the switch body ( the Closing brace that completes the switch ) This is the conventional way to build a switch statement, but the break is optional. if it is missing, our "CASE" drops through to the one after it. That is, the code for the following case statements execute until a break is encountered. Although we don't usually want this kind of behavior, it can be useful to an experienced programmer. (Read About Break Statement...)
Syntax:
The Syntax for a Switch statement in C# is as follows:
switch(Expression)
{
case Constant_Expression:
/*Statement or
Group of Statement: */
break; //optional:
case constant_Expression:
/*Statement or
Group of Statement: */
break; //optional:
/* ...
... We May have number of Statement:
...*/
default: //optional:
/*Statement or
group of Statement: */
}
Example:
Let's have an example to clear the concept of Switch Statement. in this example we will create an Program. this Program will ask Student to Enter their Grade. When student will enter their Grade, then our program will show some comment about the Grade. so let's start.
“
As we know that C# is case sensitive programming language. so "A" and "a" will be two different grades in switch statement. if case constant-expression is "A" and user Enter "a" then Switch statement will execute default statement, because there is no "a" in case constant-expression. to avoid this type of error and allow user to enter capital "A" or small "a", we can put two cases at same time having same statement for both as shown in example:
/*Example: Switch Statement: InfoBrother:*/
using System;
namespace SwitchState
{
class Program
{
static void Main(string[] args)
{
char grade; //variable declaration:
Console.WriteLine("Enter Your Grade: A, B, C or D:");
grade = Convert.ToChar(Console.ReadLine());
switch(grade)
{ //switch body begin:
case 'a':
case 'A':
Console.WriteLine("Excellent: ");
break;
case 'b':
case 'B':
Console.WriteLine("Good: ");
break;
case 'c':
case 'C':
Console.WriteLine("Fair: ");
break;
case 'd':
case 'D':
Console.WriteLine("Fail: ");
break;
default:
Console.WriteLine("Error! Enter your Grade again: ");
break;
} //switch body close:
Console.ReadKey();
}
}
}
Switch Statement:
Enter Your Grade: A, B, C or D:
A
Excellent:
----------------------------------------
Enter Your Grade: A, B, C or D:
c
Fair:
----------------------------------------
Enter Your Grade: A, B, C or D:
g
Error! Enter your Grade again:
Copy and paste this code into your compiler and try to play with code. remove "Break" statement to know how its work. put any letter other than A, B, C and D to know how "default" work.
Example:
Let's have another useful Switch Example: in this example we will create an simple calculator which can perform Addition (+), Multiplication (*), Subtraction (-), and Division (/). An Operator will be case constant-expression here, and switch expression work will based on Operator.
/*Example: Switch Statement: InfoBrother:*/
using System;
namespace SwitchState
{
class Program
{
static void Main(string[] args)
{
float a, b, result; //variable declaration:
char operation;
Console.WriteLine("Enter Your First Number: ");
a = Convert.ToInt32(Console.ReadLine()); //Enter 1st Number:
Console.WriteLine("Enter Any Operand. | + | - | * | / |: ");
operation = Convert.ToChar(Console.ReadLine()); //Enter Operator:
Console.WriteLine("Enter Your second Number: ");
b = Convert.ToInt32(Console.ReadLine()); //Enter 2nd Number:
switch(operation)
{ //switch body begin:
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
result = a / b;
break;
default:
Console.WriteLine("Error: Check Your Question Again:");
result = 0;
break;
} //switch body close:
Console.WriteLine(a.ToString() + operation +
b.ToString() + " = " + result.ToString());
Console.ReadKey();
}
}
}
Switch Statement:
Enter Your First Number:
14
Enter Any Operand. | + | - | * | / |:
+
Enter Your second Number:
5
14+5 = 19
If-else Vs Switch Statement:
If-else statement is computationally one of the most expensive statements in C# Programming language. We call it expensive due to the fact that the processor has to go through many cycles to executes an if-else statement to evaluate a Multi way decision. but if we have huge numbers of condition and need to take some action according to each condition, then if-else statements might be gone expensive. the code will be gone lengthy and less efficient.
The C# language provides us a stand-alone structure to handle these instances. This structure is "Switch Structure". the switch statement make our code more efficient and easy to read and understand as shown in example below.
if (grade == 'A')
Console.WriteLine("Excellent: ");
else if(grade == 'B')
Console.WriteLine("Very Good: ");
else if(grade == 'C')
Console.WriteLine("Good: ");
else if(grade == 'D')
Console.WriteLine("Poor: ");
else if(grade == 'E')
Console.WriteLine("Fail: ");
else
Console.WriteLine("Enter Grade Again: ");
switch(grade)
{
case 'A':
Console.WriteLine("Excellent: ");
break;
case 'B':
Console.WriteLine("Very Good: ");
break;
case 'C':
Console.WriteLine("Good: ");
break;
case 'D':
Console.WriteLine("Poor: ");
break;
case 'E':
Console.WriteLine("Fail: ");
break;
default:
Console.WriteLine("Enter Grade Again: ");
break;
}
In the above Example we create a program that will show some comments about Grade when user will enter their grade. we use If-else and switch statement to create this program. both statements will work same. but we can see that "Switch statement" is more efficient and easy to read and understand.
“
Each case can be followed by any number of statements to execute. Unlike with the if statement, the statements to be executed do not need to be contained in a block with curly braces: