Switch Case Statement in C#

Switch case statement used to evaluate the multiple conditions and execute the only matching condition and break the execution of remaining code block when the condition matches. The switch case statement is very effective when we have multiple If else conditions in the code. The If else condition compare the given value to each If -else If block condition but in the switch case statement the condition checked at the entry point of switch case method and control goes to exactly the case which needs to be executed instead of checking each condition in the written code block statement

Syntax C# Switch Case Statement

switch(SwitchCaseConditionValue) 
{
  case A:
    // logic implementation code for case A
    break;
  case B:
    // logic implementation code for case B
    break;
 case C:
    // logic implementation code for case C
    break;
  default:
    //logic implementation code if non of the condition match
    break;
}

Realtime Example of C# Switch Case Statement

Suppose we have requirement to identify the currency description based on the given particular country currency code

using System;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string CurrencyCode = "SGD";
         
            switch (CurrencyCode)
            {
                case "INR":
                    Console.WriteLine("Indian Rupee	₹");
                    break;
                case "USD":
                    Console.WriteLine("United States Dollar $");
                    break;
                case "SGD":
                    Console.WriteLine("Singapore Dollar $");
                    break;
                default:
                    Console.WriteLine("Currency Code not Matching");
                    break;
            }
           
            Console.ReadLine();
        }
    }
}

In the preceding example the input value is SGD when you run this program we will get the following output


Key Points of C# Switch Case Statement

  • Switch case statement suitable for executing multiple conditions & execute the true block once
  • Switch case statement does not check each case condition, it evaluates which block to execute at the entry point of switch expression execution
  • Switch expression does not allow the logical conditions 
  • Break statement must be written after each case block to stop the execution of the code its saves the lots of time to execute the rest code in the given statement
  • Default case is useful when none of the condition matches on given value

Summary

Hope this article is useful to understand about the C# switch case statement, in next article we will learn about the difference between the If else and switch case statement.

Post a Comment

www.CodeNirvana.in

Protected by Copyscape
Copyright © Compilemode