C# Switch statement

Aug 9th 2020 ‧ 3 minutes read
#C-sharp
#Dotnet

The switch statement is a type of selection statement which performs an action according to the condition. The switch statement used to select one condition among many.

The switch statement can be used as an alternative to the if-statement if there are too many possible cases. It provides a descriptive way to write if-else statements.

Syntax

switch (number){

   case a:
      // Do something for 'a'
   case b:
      // Do something for 'b'
   ...
   case n:
     // Do something for 'n'
   default:
     // Do something none of the cases match.

}

Example

using System;

namespace SwitchCase
{
    class Program
    {
        static void Main(string[] args)
        {
            int number = 3;

            switch (number)
            {
                case 1:
                    Console.WriteLine("It's One");
                    break;
                case 2:
                    Console.WriteLine("It's two");
                    break;
                case 3:
                    Console.WriteLine("It's three");
                    break;

                default:
                    Console.WriteLine("It's Default");
                    break;
            }
        }
    }
}

The above program will print the output as

It's three

The 'break' keyword

The break keyword is used to breaks out of the switch block. It is used to stop the further comparison of cases inside the switch block. In C# the break statement is required otherwise, the code generates a compiler error as

Program.cs(16,17): error CS0163: Control cannot fall through from one case label ('case 2:') to another

The build failed. Fix the build errors and run again.

You can also use return and goto to breaks out of the switch statement.

The 'default' keyword

The default keyword is optional and used to execute some code block if there is no match for the cases.

Share article