C# switch statement


C# switch statement The C# switch proclamation executes one explanation from various conditions. It resembles if-else-if stepping stool proclamation in C#.

The expression utilized in a switch explanation must have a necessary or listed sort, or be of a class type in which the class has a solitary change capacity to an indispensable or identified sort.

You can have any number of case explanations inside a switch. Each case is trailed by the incentive to be contrasted with and a colon.

The consistent articulation for a case must be similar information type as the variable in the switch, and it must be steady or strict.

At the point when the variable being turned on is equivalent to a case, the announcements following that case will execute until a break proclamation is reached.

At the point when a break proclamation is reached, the switch ends, and the progression of control hops to the following line following the switch explanation.

A few out of every odd case needs to contain a break. On the off chance that no break shows up, at that point, it will raise an assemble time mistake.

A switch articulation can have a discretionary default case, which must show up toward the finish of the switch. The default case can be utilized for playing out an assignment when none of the cases is valid.

C# switch statement
C# switch statement

structure:

switch(expression){    
case value1:    
 //code to be executed;    
 break;  
case value2:    
 //code to be executed;    
 break;  
......    
    
default:     
 //code to be executed if all cases are not matched;    
 break;  
}   

Example

using System;

namespace DecisionMaking {
   class Program {
      static void Main(string[] args) {
         /* local variable definition */
         char grade = 'B';
         
         switch (grade) {
            case 'A':
               Console.WriteLine("Excellent!");
               break;
            case 'B':
            case 'C':
               Console.WriteLine("Well done");
               break;
            case 'D':
               Console.WriteLine("You passed");
               break;
            case 'F':
               Console.WriteLine("Better try again");
               break;
               default:
            Console.WriteLine("Invalid grade");
               break;
         }
         Console.WriteLine("Your grade is  {0}", grade);
         Console.ReadLine();
      }
   }
}

Output:

well done

your grade is 8

Have any Question or Comment?

Leave a Reply

Your email address will not be published. Required fields are marked *

Categories

%d bloggers like this: