C# Switch Statement

Updated on     Kisan Patel

The switch statement executes one or more of a series of cases, based on the value of a controlling expression.

The switch-case statement has the following syntax.

switch (test_expression)
{
   case expression1:
           statement1; // This statement is executed when expression1 is correct
           break;

   case expression2:
           statement2; // This statement is executed when expression2 is correct
           break;
   .....
   Default:
           statement; //This statement is executed when all previous expression is false
}

To exit from switch statement C# programmer must have the break statement at the end of each case.

using System;

namespace ConsoleApp
{
    class SwitchDemo
    {
        static void Main(string[] args)
        {
            int i = 3;

            switch(i)
            {
                case 1:
                    Console.WriteLine("one");
                    break;
                case 2:
                    Console.WriteLine("two");
                    break;
                case 3:
                    Console.WriteLine("three");
                    break;
                case 4:
                    Console.WriteLine("four");
                    break;
                default:
                    Console.WriteLine("None of the about");
                    break;
            }
        }
    }
}

The output of the above C# program…

c-sharp-switch-case-demo


C#

Leave a Reply