DEV Community

Cover image for C# Switch statement
Ishaan Sheikh
Ishaan Sheikh

Posted on • Edited on

C# Switch statement

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.

}
Enter fullscreen mode Exit fullscreen mode

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;
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

The above program will print the output as

It's three
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

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.

💡 One last tip before you go

Tired of spending so much on your side projects? 🤔

We have created a membership program that helps cap your costs so you can build and experiment for less. And we currently have early-bird pricing which makes it an even better value! 🐥

Check out DEV++

Top comments (0)

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay