C# Switch

C# switch statement is used to execute a block of statements among different blocks, based on the matching of an expression with case value.

Syntax of switch statement

Following is the syntax of C# switch statement.

switch(match_expression) {
		case value1:
			statement(s);
			break;
		case value2:
			statement(s);
			break;
		case valueN:
			statement(s);
			break;
		default:
			statement(s);
			break;
	}

match_expression should evaluate to a non-null value.

There could be multiple case blocks.

Each case block ends with a break statement.

The default block is optional. When no case block is executed, default block is executed.

No two case blocks can have the same matching value. It could result in a build error.

Example 1 – C# Switch

Following is a simple example for C# switch.

Program.cs

using System;

namespace CSharpExamples {

    class Program {
        static void Main(string[] args) {
            Console.Write("Enter a value [1-3]: ");
            int a = Convert.ToInt32(Console.ReadLine());

            switch(a){
                case 1:
                    Console.WriteLine("One");
                    break;
                case 2:
                    Console.WriteLine("Two");
                    break;
                case 3:
                    Console.WriteLine("One");
                    break;
            }
        }
    }
}

Output

PS D:\workspace\csharp\HelloWorld> dotnet run
Enter a value [1-3]: 2
Two

In this example, 2 is given as input. match_expression is 2. So the case block with matching value 2 is run.

Switch with Multiple Cases containing same Matching Value

When you write case statements with a same matching value, you will get a build error.

Program.cs

using System;

namespace CSharpExamples {

    class Program {
        static void Main(string[] args) {
            Console.Write("Enter a value [1-3]: ");
            int a = Convert.ToInt32(Console.ReadLine());

            switch(a){
                case 1:
                    Console.WriteLine("One");
                    break;
                case 1:
                    Console.WriteLine("One");
                    break;
                case 3:
                    Console.WriteLine("One");
                    break;
            }
        }
    }
}

Output

PS D:\workspace\csharp\HelloWorld> dotnet run
Program.cs(14,17): error CS0152: The switch statement contains multiple cases with the label value '1' [D:\workspace\csharp\HelloWorld\HelloWorld.csproj]

The build failed. Please fix the build errors and run again.