Switch Statement in C#

The switch statement is used to branch your code based on the value of an expression.

Syntax of Switch in C# 

switch (expression)
{
    case value1:
        // Code to execute if expression equals value1
        break;
    case value2:
        // Code to execute if expression equals value2
        break;
    // More case statements as needed
    default:
        // Code to execute if expression does not match any case
        break;
}

Example of Switch in C#

int number = 1;
switch (number)
{
    case 0:
        Console.WriteLine("Zero");
        break;
    case 1:
        Console.WriteLine("One");
        break;
    case 2:
        Console.WriteLine("Two");
        break;
    case 3:
        Console.WriteLine("Three");
        break;
    default:
        Console.WriteLine("No numbers matching");
        break;
}

The result will be One.

In this code:

    The number variable is set to 1.
    The switch statement evaluates the value of number.
    If number is 0, it prints "Zero".
    If number is 1, it prints "One".
    If number is 2, it prints "Two".
    If number is 3, it prints "Three".
    If number doesn't match any of these cases, it prints "No numbers matching".

Since number is set to 1 in this example, it will print "One" to the console.


Similar Articles