The switch Statement

Learning Resources
 

The switch Statement


The switch statement is unlike the if-statement. It requires that each case be constant. This constraint allows various optimizations in the lower-level intermediate representation. Some optimizations are jump tables and, for strings, Dictionary collections. Switch speeds up certain parts of your C# program.

Int example
To start, this program demonstrates the syntax of a simple switch statement in the C# language. It reveals the core concept of a selection statement based on constant case values. We switch on an int here.

using System;

class Program
{
    static void Main()
    {
    int value = 5;
    switch (value)
    {
        case 1:
        Console.WriteLine(1);
        break;
        case 5:
        Console.WriteLine(5);
        break;
    }
    }
}

Output

5

Example 2

Next we see an example of the switch statement that includes curly brackets and the default case. The program accepts an int from the user and then tests it for six different values.

Note: You see how the curly brackets { } can be used in the switch cases, and how you can combine the case statements.

class Program
{
    static void Main()
    {
    while (true)
    {
        System.Console.WriteLine("Type number and press Return");
        try
        {
        int i = int.Parse(System.Console.ReadLine());
        switch (i)
        {
            case 0:
            case 1:
            case 2:
            {
                System.Console.WriteLine("Low number");
                break;
            }
            case 3:
            case 4:
            case 5:
            {
                System.Console.WriteLine("Medium number");
                break;
            }
            default:
            {
                System.Console.WriteLine("Other number");
                break;
            }
        }
        }
        catch
        {
        }
    }
    }
}

Output
    1. Input from console application is parsed.
    2. Switch statement selects a case based on input.

 

 For Support