C# Switch Tutorial For Beginners With Examples

A switch is a simple yet powerful statement that allows C# programs to take decisions based on certain conditions.

C# switch Syntax

A switch statement has a switch section inside which number of case labels are present.
switch (expression)
{
    case constant1:
        Console.WriteLine("Perform Action1.");
        break;
    case constant2:
        Console.WriteLine("Perform Action2.");
        break;
    default:
        Console.WriteLine("Perform default Action.");
        break;
}              
A switch expression is always evaluated against the constant values specified by the case labels. If a matching constant value is not found then the control is transferred to the defaultsection. If no default section is found then the control goes out of the switch statement.
In the below example the control is transferred to the default section as a matching name is not found.
    string planetName = "Earth";

    switch (planetName)
    {
        case "Jupiter":
            Console.WriteLine("Color of planet is yellow.");
            break;
        case "Mars":
            Console.WriteLine("Color of planet is red.");
            break;
        default:
            Console.WriteLine("Planet name not found.");
            break;
    }
        
To exit a switch statement a break statement is used. The break statement ends the execution and moves the control out of the current code block being executed.
The break statement is an optional statement and if it is not used then the code execution inside a switch statement continues sequentially.

C# Nested switch statement

In C# the switch statements can contain any number of switch statements inside it and these switch statements can have one or more case labels.
    string planetName = "Mars";
    bool biggerThanEarth = false;

    switch (planetName)
    {
        case "Jupiter":
            Console.WriteLine("Color of planet is yellow.");
            break;
        case "Mars":
            switch(biggerThanEarth)
            {
                case true:
                    Console.WriteLine("Mars is bigger than Earth.");
                    break;
                case false:
                    Console.WriteLine("Mars is smaller than Earth.");
                    break;
            }

            Console.WriteLine("Color of planet is red.");
            break;

        default:
            Console.WriteLine("Planet name not found.");
            break;
    }