CSharp - Statement switch statement

Introduction

switch statements runs code on a list of possible values.

This example demonstrates the most common scenario, which is switching on constants.

int cardNumber = 12;
     
switch (cardNumber)
{
         case 13:
           Console.WriteLine ("King");
           break;
         case 12:
           Console.WriteLine ("Queen");
           break;
         case 11:
           Console.WriteLine ("Jack");
           break;
         case -1:                         // Joker is -1
           goto case 12;                  // In this game joker counts as queen
         default:                         // Executes for any other cardNumber
           Console.WriteLine (cardNumber);
           break;
}

When you are using a constant, you can only use the built-in integral types, bool, char, enum types, and the string type.

For each case you have the following options:

Option Description
breakjumps to the end of the switch statement
goto case x jumps to another case clause
goto default jumps to the default clause
Any otherjump statement-namely, return, throw, continue, or goto label

When more than one value should execute the same code, list the common cases sequentially:

switch (cardNumber)
{
       case 13:
       case 12:
       case 11:
         Console.WriteLine ("Face card");
         break;
       default:
         Console.WriteLine ("Plain card");
         break;
}

The following code uses switch statement to branch out grade scales.

Demo

using System;

class Program/*  ww w.java 2s .  com*/
{
    static void Main(string[] args)
    {
        Console.WriteLine("1-Below 40");
        Console.WriteLine("2-Between 41 and 60");
        Console.WriteLine("3-Between 60 and 79");
        Console.WriteLine("4-Above 80");
        Console.WriteLine("Enter your score");
        int score = int.Parse(Console.ReadLine());
        switch (score)
        {
            case 1:
                Console.WriteLine("Poor performance");
                break;
            case 2:
                Console.WriteLine("Average performance");
                break;
            case 3:
                Console.WriteLine("Good performance");
                break;
            case 4:
                Console.WriteLine("Excellent performance");
                break;
            default:
                break;
        }
    }
}

Result

Quiz

Exercise