๐ŸŽ“ A1Learner
๐Ÿ”
0 of 41 lessons completed

C# Switch

A switch statement is code that matches one value against a list of cases. The case with the matching value runs its statements.

Matching one case

The value 3 matches case 3. That case prints its day name.

using System;

class Program
{
    static void Main(string[] args)
    {
        int day = 3;
        switch (day)
        {
            case 1:
                Console.WriteLine("Monday");
                break;
            case 2:
                Console.WriteLine("Tuesday");
                break;
            case 3:
                Console.WriteLine("Wednesday");
                break;
        }
    }
}

The default case

The value 9 matches no case here. The default case runs.

using System;

class Program
{
    static void Main(string[] args)
    {
        int day = 9;
        switch (day)
        {
            case 1:
                Console.WriteLine("Monday");
                break;
            case 2:
                Console.WriteLine("Tuesday");
                break;
            default:
                Console.WriteLine("Unknown day");
                break;
        }
    }
}

A missing break

This code has no break after case 1. The compiler refuses it and reports an error.

using System;

class Program
{
    static void Main(string[] args)
    {
        int day = 1;
        switch (day)
        {
            case 1:
                Console.WriteLine("Monday");
            case 2:
                Console.WriteLine("Tuesday");
                break;
        }
    }
}

Example

using System;

class Program
{
    static void Main(string[] args)
    {
        char grade = 'B';
        switch (grade)
        {
            case 'A':
                Console.WriteLine("Excellent");
                break;
            case 'B':
                Console.WriteLine("Good");
                break;
            case 'C':
                Console.WriteLine("Fair");
                break;
            default:
                Console.WriteLine("Try again");
                break;
        }
    }
}

Key points

  • Each case names one value to match.
  • A break ends a case and leaves the switch.
  • The default case runs when no case matches.
  • A case with statements must end with break.

In this example, grade holds the char B. The switch compares it with each case in order. Case B is the first match. Its statements print "Good". The break then leaves the switch.

Note

C# stops a case from falling into the next case, and the compiler reports error CS0163.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does the default case do?