C# Switch

Selecting from multiple options

πŸ”€ What is a Switch Statement?

The switch statement selects one of many code blocks to execute based on a value. It's a cleaner alternative to multiple if-else statements when checking one variable against many values.


// Simple switch example
int day = 3;
switch (day)
{
    case 1:
        Console.WriteLine("Monday");
        break;
    case 3:
        Console.WriteLine("Wednesday");
        break;
}
                                    

Output:

Wednesday

Switch Components

🎯

Case Labels

Define possible values to match

case 1:
    Console.WriteLine("One");
    break;
πŸ›‘

Break Statement

Exit the switch block

case 2:
    Console.WriteLine("Two");
    break;
πŸ“Œ

Default Case

Runs if no case matches

default:
    Console.WriteLine("Other");
    break;
πŸ”—

Multiple Cases

Group cases together

case 1:
case 2:
    Console.WriteLine("1 or 2");
    break;

πŸ”Ή Basic Switch Statement

The switch statement in C# evaluates a single expression and compares it against multiple case labels to execute different code blocks. It provides a cleaner, more organized alternative to long if-else chains when checking discrete values. For example, switch (day) { case 1: Console.WriteLine("Monday"); break; }. Each case must end with a break (or other jump statement) to prevent fall-through. Switch statements enhance code readability and performance for multi-branch decisions, commonly used in menu systems, state machines, and command dispatchers.

int dayNumber = 4;

switch (dayNumber)
{
    case 1:
        Console.WriteLine("Monday");
        break;
    case 2:
        Console.WriteLine("Tuesday");
        break;
    case 3:
        Console.WriteLine("Wednesday");
        break;
    case 4:
        Console.WriteLine("Thursday");
        break;
    case 5:
        Console.WriteLine("Friday");
        break;
    default:
        Console.WriteLine("Weekend");
        break;
}

Output:

Thursday

πŸ”Ή The Default Case

The default case in a switch statement executes when no other case matches the evaluated expression. Acting as a catch-all similar to else in if-else chains, it handles unexpected or invalid values gracefully. For instance, default: Console.WriteLine("Invalid option"); break;. Including a default case is considered good practice for robustness, as it ensures the program responds appropriately to all possible inputs, improving error handling and user experience. It’s typically placed last but can appear anywhere within the switch block.

char grade = 'B';

switch (grade)
{
    case 'A':
        Console.WriteLine("Excellent!");
        break;
    case 'B':
        Console.WriteLine("Good job!");
        break;
    case 'C':
        Console.WriteLine("Well done");
        break;
    case 'D':
        Console.WriteLine("You passed");
        break;
    case 'F':
        Console.WriteLine("Better try again");
        break;
    default:
        Console.WriteLine("Invalid grade");
        break;
}

// Example with number
int month = 13;
switch (month)
{
    case 12:
    case 1:
    case 2:
        Console.WriteLine("Winter");
        break;
    default:
        Console.WriteLine("Invalid month number");
        break;
}

Output:

Good job!

Invalid month number

πŸ”Ή Multiple Cases

Multiple cases in a C# switch statement can share the same code block by stacking case labels without intervening statements. This technique groups several values that should trigger identical logic, reducing code duplication. For example, case 1: case 2: case 3: Console.WriteLine("Small number"); break;. It’s especially useful for ranges or categories, like treating multiple inputs as "weekend" or "weekday". This approach maintains the readability and efficiency of switch while accommodating scenarios where multiple distinct values lead to the same outcome.

int month = 7;

switch (month)
{
    case 12:
    case 1:
    case 2:
        Console.WriteLine("Winter");
        break;
    case 3:
    case 4:
    case 5:
        Console.WriteLine("Spring");
        break;
    case 6:
    case 7:
    case 8:
        Console.WriteLine("Summer");
        break;
    case 9:
    case 10:
    case 11:
        Console.WriteLine("Fall");
        break;
    default:
        Console.WriteLine("Invalid month");
        break;
}

// Weekend checker
int day = 6;
switch (day)
{
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
        Console.WriteLine("Weekday");
        break;
    case 6:
    case 7:
        Console.WriteLine("Weekend");
        break;
}

Output:

Summer

Weekend

πŸ”Ή Switch with Strings

C# switch statements fully support string comparisons, enabling clean branching based on textual input. Each case can specify a string literal, and matching is case-sensitive by default. For example, switch (command) { case "start": Start(); break; }. This is ideal for command processors, menu selections, or configuration parsing. For case-insensitive matching, combine with StringComparison or convert strings to a uniform case beforehand. String-based switches enhance code clarity over multiple if-else conditions, making them a go-to for handling discrete text-based options.

string command = "start";

switch (command)
{
    case "start":
        Console.WriteLine("Starting the program...");
        break;
    case "stop":
        Console.WriteLine("Stopping the program...");
        break;
    case "pause":
        Console.WriteLine("Pausing the program...");
        break;
    case "restart":
        Console.WriteLine("Restarting the program...");
        break;
    default:
        Console.WriteLine("Unknown command");
        break;
}

// User role example
string role = "admin";
switch (role)
{
    case "admin":
        Console.WriteLine("Full access granted");
        break;
    case "user":
        Console.WriteLine("Limited access granted");
        break;
    case "guest":
        Console.WriteLine("Read-only access");
        break;
    default:
        Console.WriteLine("Access denied");
        break;
}

Output:

Starting the program...

Full access granted

πŸ”Ή Switch vs If-Else

Choosing between switch and if-else in C# depends on the scenario: switch excels for discrete value matching, while if-else handles complex conditions and ranges. Switch offers better readability and potential performance benefits when checking a single variable against many constant values. If-else is more flexible, supporting relational operators, pattern matching, and boolean logic. Use switch for menus, enums, or states; use if-else for dynamic comparisons, range checks, or multiple condition evaluations. Understanding both structures allows for optimal, maintainable decision logic.

// Using if-else (more verbose)
int number = 2;
if (number == 1)
{
    Console.WriteLine("One");
}
else if (number == 2)
{
    Console.WriteLine("Two");
}
else if (number == 3)
{
    Console.WriteLine("Three");
}
else
{
    Console.WriteLine("Other");
}

// Using switch (cleaner)
int number2 = 2;
switch (number2)
{
    case 1:
        Console.WriteLine("One");
        break;
    case 2:
        Console.WriteLine("Two");
        break;
    case 3:
        Console.WriteLine("Three");
        break;
    default:
        Console.WriteLine("Other");
        break;
}

Output:

Two

Two

πŸ”Ή Practical Examples

While loops are fundamental for real-world programming tasks where repetition is conditional. Key applications include input validation (re-prompting a user until correct data is entered), accumulating a sum until a threshold is met, implementing password attempts with limited tries, or running a main game loop. Their flexibility makes them suitable for event-driven programming, processing streams of data, and controlling program states where the exact number of required repetitions cannot be predetermined before runtime.

// Simple calculator
char operation = '+';
int a = 10, b = 5;

switch (operation)
{
    case '+':
        Console.WriteLine($"Result: {a + b}");
        break;
    case '-':
        Console.WriteLine($"Result: {a - b}");
        break;
    case '*':
        Console.WriteLine($"Result: {a * b}");
        break;
    case '/':
        Console.WriteLine($"Result: {a / b}");
        break;
    default:
        Console.WriteLine("Invalid operation");
        break;
}

// Traffic light system
string light = "yellow";
switch (light)
{
    case "red":
        Console.WriteLine("Stop!");
        break;
    case "yellow":
        Console.WriteLine("Slow down");
        break;
    case "green":
        Console.WriteLine("Go");
        break;
    default:
        Console.WriteLine("Light malfunction");
        break;
}

Output:

Result: 15

Slow down

🧠 Test Your Knowledge

What keyword is used to exit a switch case?