Topic : Switch Statement in C# Programming Language:

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.



Switch Statement: infobrother

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: */

            }


  • There are some rules for switch Statement:

    » The Expression used in switch statement must have an integral or enumerated type, or be of a class type in which the class has a single conversion function to an integral or enumerated type.
    » We can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.
    » The constant-Expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal.
    » When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
    » When a Break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.
    » Not every case Needs to contain a break. if no break appears, the flow of control will fall through to subsequent cases until a break is reached.
    » A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the case is true. No break is needed in the default case.



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();
        }
    }
}


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();
        }
    }
}


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:

















I Tried my Best to Provide you complete Information regarding this topic in very easy and conceptual way. but still if you have any Problem to understand this topic, or do you have any Questions, Feel Free to Ask Question. i'll do my best to Provide you what you need.

Sardar Omar.
InfoBrother





WRITE FOR INFOBROTHER

Advertising






Advertisement