What is difference between using if/else and switch-case in C#?


Switch is a selection statement that chooses a single switch section to execute from a list of candidates based on a pattern match with the match expression.

The switch statement is often used as an alternative to an if-else construct if a single expression is tested against three or more conditions.

Switch statement is quicker. The switch statement the average number of comparisons will be one regardless of how many different cases you have So lookup of an arbitrary case is O(1)

Using Switch 

Example

class Program{
public enum Fruits { Red, Green, Blue }
public static void Main(){
   Fruits c = (Fruits)(new Random()).Next(0, 3);
   switch (c){
      case Fruits.Red:
         Console.WriteLine("The Fruits is red");
         break;
      case Fruits.Green:
         Console.WriteLine("The Fruits is green");
         break;
      case Fruits.Blue:
         Console.WriteLine("The Fruits is blue");
         break;
      default:
         Console.WriteLine("The Fruits is unknown.");
         break;
   }
   Console.ReadLine();
}
Using If else
class Program{
   public enum Fruits { Red, Green, Blue }
   public static void Main(){
      Fruits c = (Fruits)(new Random()).Next(0, 3);
      if (c == Fruits.Red)
         Console.WriteLine("The Fruits is red");
      else if (c == Fruits.Green)
         Console.WriteLine("The Fruits is green");
      else if (c == Fruits.Blue)
         Console.WriteLine("The Fruits is blue");
      else
         Console.WriteLine("The Fruits is unknown.");
      Console.ReadLine();
   }
}

Updated on: 19-Aug-2020

313 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements