C# Switch Statement Example

  • C#
  • 1 min read

The switch statement is an alternative to the nested if-else statement in C#. When there are complex choices to make then you can use SWITCH statement to make the program easily readable.

Syntax

switch (expression)
{
case constant-expression:
statement
jump-statement
[default: statement]
}

Switch Statment Example in C#

using System;
class SwitchStatement
{
    enum Party
    {
        Democrat,
        ConservativeRepublican,
        Republican,
        Libertarian,
        Liberal,
        Progressive,
    };
    static void Main(string[] args)
    {
        Party myChoice = Party.Libertarian;
        switch (myChoice)
        {
            case Party.Democrat:
                Console.WriteLine("You voted Democratic.\n");
                break;
            case Party.ConservativeRepublican: // fall through
            //Console.WriteLine(
            //"Conservative Republicans are voting Republican\n");
            case Party.Republican:
                Console.WriteLine("You voted Republican.\n");
                break;
            case Party.Liberal:
                Console.WriteLine(" Liberal is now Progressive");
                goto case Party.Progressive;
            case Party.Progressive:
                Console.WriteLine("You voted Progressive.\n");
                break;
            case Party.Libertarian:
                Console.WriteLine("Libertarians are voting Democratic");
                goto case Party.Democrat;
            default:
                Console.WriteLine("You have not picked a valid choice.\n");
                break;
        }
        Console.WriteLine("Thank you for voting.");
        Console.ReadLine();
    }
}

Output

Libertarians are voting Democratic
You voted Democratic.

Thanks for voting.

See also: