C Sharp switch

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

C# switch

The C# switch statement executes one statement from multiple conditions. It is like if-else-if ladder statement in C#.

Syntax:

  1. switch(expression){    
  2. case value1:    
  3.  //code to be executed;    
  4.  break;  
  5. case value2:    
  6.  //code to be executed;    
  7.  break;  
  8. ......    
  9.     
  10. default:     
  11.  //code to be executed if all cases are not matched;    
  12.  break;  
  13. }    

 

C# switch statement flow

C# Switch Example

  1. using System;  
  2.   public class SwitchExample  
  3.     {  
  4.       public static void Main(string[] args)  
  5.       {  
  6.           Console.WriteLine("Enter a number:");  
  7.           int num = Convert.ToInt32(Console.ReadLine());  
  8.   
  9.           switch (num)  
  10.           {  
  11.               case 10: Console.WriteLine("It is 10"); break;  
  12.               case 20: Console.WriteLine("It is 20"); break;  
  13.               case 30: Console.WriteLine("It is 30"); break;  
  14.               default: Console.WriteLine("Not 10, 20 or 30"); break;  
  15.           }  
  16.       }  
  17.     }  

Output:

Enter a number:
10
It is 10

Output:

Enter a number:
55
Not 10, 20 or 30

Note: In C#, break statement is must in switch cases.