← Back to C# Course | Chapter 4: Control Flow | Lesson 2 of 7

switch Statement

A switch is like a menu where you say the item number and get exactly that dish. C# compares one value against a list of cases and runs the one that matches.

In this page:

  1. switch Statement
Syntax
csharp
switch (value)
{
    case value1:
        // ...
        break;
    case value2:
        // ...
        break;
    default:
        // no case matched
        break;
}

switch Statement

A switch statement compares one value against several case labels and runs the matching block. Each case needs a break (or return) to prevent falling through to the next one. default handles any value that doesn't match a case.

Warning: Unlike C, C# does not allow implicit fallthrough between non-empty cases — each case must end with break, return, or goto.

Example: switch Statement

markup
using System;

class Program
{
    static void Main(string[] args)
    {
        int day = 3;
        string name;

        switch (day)
        {
            case 1:
                name = "Monday";
                break;
            case 2:
                name = "Tuesday";
                break;
            case 3:
                name = "Wednesday";
                break;
            default:
                name = "Unknown";
                break;
        }

        Console.WriteLine(name);
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting break at the end of a case, which is a compile error in C# because falling through is not allowed.
  2. Not adding a default case for unexpected values.
  3. Using a non-constant value in a case label, when labels must be constants.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.