Strings in switch Statements


Strings can be used in switch statements. The string type is the only non-integer type that can be used to control a switch statement. The next program illustrates a switch statement involving strings.

// String4 - Strings in switch statments

using System;

class Program
{
    static void Main()
    {
        string S = "Hello world";
        
        switch (S)
        {
            case "Hello world":
                Console.WriteLine("Hello world");
                break;

            case "Goodbye world":
                Console.WriteLine("Goodbye world");
                break;

            default:
                Console.WriteLine("Unknown string");
                break;
        }
    }
 }

"Hello world" is printed out to the console.