C Sharp Switch

C# switch

To execute one statement from multiple conditions, either the switch statement or the if-else-if ladder statement can be used in C#. The use of the break statement is a must in the C# switch statement.

Syntax:

switch(expression){    
case 1:    
 //code to be executed;    
 break;  
case 2:    
 //code to be executed;    
 break;  
......    
default:     
 //code to be executed if none of the cases matched;    
 break;  
}    

Example:

using System;  
  public class Example  
    {  
      public static void Main(string[] args)  
      {  
          Console.WriteLine("Enter a number:");  
          int n = Convert.ToInt32(Console.ReadLine());  
 
          switch (n)  
          {  
              case 0: Console.WriteLine("Not Prime!!"); 
				  break;  
              case 1: Console.WriteLine("Not Prime!!"); 
				  break;  
              case 2: Console.WriteLine("Prime!!"); 
				  break;  
              default: Console.WriteLine("Enter either 0, 1 or 2"); 
				  break;  
          }  
      }  
    }

Output 1:

Output 2:

Output 3:

Explanation:

In the above example, we are displaying the working and the behavior of the C# Switch statement.