DEV Community

Sabin Sim
Sabin Sim

Posted on

16. C# (Switch Statement)

0. The Real Goal of This Lesson

This is not about learning syntax.

The real goal is to understand one idea physically:

“How to split execution flow into multiple exact branches based on a single value.”

If this is not clear:

  • switch becomes just another keyword
  • break feels arbitrary
  • Control flow design remains shallow

Everything turns into memorized structure instead of intentional logic.


1. Why Do We Need switch?

Let’s start with a problem.

❌ Using if / else

if (choice == "A")
{
    Console.WriteLine("Add");
}
else if (choice == "S")
{
    Console.WriteLine("Subtract");
}
else if (choice == "M")
{
    Console.WriteLine("Multiply");
}
else
{
    Console.WriteLine("Invalid choice");
}
Enter fullscreen mode Exit fullscreen mode

Logically, there is nothing wrong here.

The program works.

But structurally:

  • The same variable is compared repeatedly
  • The pattern must be mentally reconstructed by the reader
  • The intent is not immediately visible

The structure says “conditional logic.”

But the intent is actually “exact value matching.”


When switch Is the Right Tool

switch is used when:

One single value
Must be matched against multiple exact possibilities.

For example:

  • Is choice equal to "A"?
  • Is it equal to "S"?
  • Is it equal to "M"?
  • Or none of them?

This is not range logic.

This is exact matching logic.

That is what switch models.


2. The Basic Structure of switch

switch (expression)
{
    case value1:
        // code
        break;

    case value2:
        // code
        break;

    default:
        // fallback
        break;
}
Enter fullscreen mode Exit fullscreen mode

Key Concept: What Is an Expression?

An expression is:

Any code that evaluates to a value.

Examples:

  • A variable
  • A method call
  • A calculation

For example:

switch (choice)
Enter fullscreen mode Exit fullscreen mode

Here, choice is the expression.

It is evaluated once.

Its result is compared against each case label.


3. TODO App Example — Full Runnable Code

Run this directly in Rider.

using System;

class Program
{
    static void Main()
    {
        Console.WriteLine("Choose option: A, S, M");
        string choice = Console.ReadLine();

        switch (choice)
        {
            case "A":
                Console.WriteLine("Addition selected");
                break;

            case "S":
                Console.WriteLine("Subtraction selected");
                break;

            case "M":
                Console.WriteLine("Multiplication selected");
                break;

            default:
                Console.WriteLine("Invalid choice");
                break;
        }

        Console.ReadKey();
    }
}
Enter fullscreen mode Exit fullscreen mode

Notice the structure:

Evaluate once → Match exactly → Execute → Exit

That is the model.


4. Why Is break Required?

This is critical.

By default, switch behaves like this:

Once a matching case is found, execution continues downward unless explicitly stopped.

That means without break, execution “falls through” to the next case.


Try This

Remove break from one case:

case "A":
    Console.WriteLine("Addition selected");
Enter fullscreen mode Exit fullscreen mode

Run the program.

You will see additional cases executing.

This is not a bug.

This is how switch works.


The Rule

Each case must end with:

  • break
  • or return

Otherwise, control continues to the next case.

break exits the switch block.

return exits the entire method.

These are not interchangeable concepts.


5. The Exact Meaning of default

default means:

Execute this block if none of the cases match.

It is equivalent to else in an if/else structure.

It guarantees that unmatched input is handled.

Without default, unmatched input is silently ignored.

That is rarely desirable.


6. Handling Case Sensitivity

This works:

case "A":
case "a":
    Console.WriteLine("Addition selected");
    break;
Enter fullscreen mode Exit fullscreen mode

Multiple case labels can share one block.

This means:

If either value matches, execute the same logic.


Cleaner Approach (Recommended)

switch (choice.ToUpper())
Enter fullscreen mode Exit fullscreen mode

Now:

  • "a" becomes "A"
  • "A" remains "A"

You only need one case.

This reduces duplication.


7. Grade Conversion Exercise

using System;

class Program
{
    static void Main()
    {
        Console.WriteLine("Enter score (0-10):");
        int points = int.Parse(Console.ReadLine());

        string grade = ConvertPointsToGrade(points);

        Console.WriteLine($"Grade: {grade}");
        Console.ReadKey();
    }

    static string ConvertPointsToGrade(int points)
    {
        switch (points)
        {
            case 9:
            case 10:
                return "A";

            case 7:
            case 8:
                return "B";

            case 5:
            case 6:
                return "C";

            case 3:
            case 4:
                return "D";

            case 0:
            case 1:
            case 2:
                return "F";

            default:
                return "!";
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Important observation:

When using return, break is unnecessary.

Because:

return terminates the entire method immediately.

Control does not return to the switch.


8. When to Use switch vs if

Situation Recommended
Single value exact match switch
Range comparison (>, <, >=) if
Complex logical expressions if

Use the tool that matches the logical structure of the problem.

Not the tool you feel more comfortable with.


9. The Sensory Model You Must Develop

switch is:

A structure for routing execution based on one evaluated value.

if is:

A structure for evaluating logical conditions.

They are not interchangeable.

They represent different mental models.


One-Line Summary

A switch statement evaluates one expression
and dispatches execution to exactly matching branches
with explicit control over termination.

Top comments (0)