C# Switch Statement

C# Switch Statement

The C# switch statement executes one statement from multiple conditions. It is like if-else-if ladder statement in C#.

switch statements can branch program execution based on a selection of possible values.

 

1 - Syntax of C# Switch Statement

The syntax for a C# switch statement is as follows:

switch(expression) 
{
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
    break;
}

This is how it works:

  • The switch expression is evaluated once
  • The value of the expression is compared with the values of each case
  • If there is a match, the associated block of code is executed
  • The break and default keywords will be described later in this chapter

 

The switch expression is of integer type such as: int, char, byte, or short, or of an enum type, or of string type

The expression is checked for different cases and the one match is executed.

At the end of each case clause, we must set where execution is to go next, with a jump statement.

For each case you have the following options:

  • break: jumps to the end of the switch statement
  • goto case x: jumps to another case clause
  • goto default: jumps to the default clause
  • Any other: jump 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;
}

Important points to remember:

  • In C#, duplicate case values are not allowed.
  • The data type of the variable in the switch and value of a case must be of the same type.
  • The value of a case must be a constant or a literal. Variables are not allowed.
  • The break in switch statement is used to terminate the current sequence.
  • The default statement is optional and it can be used anywhere inside the switch statement.
  • Multiple default statements are not allowed.

 

2 - C# Switch Statement Flow Diagram

The following flowchart illustrates how the c# switch statement works:

C# Switch Statement Flow Diagram

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FirstProgram
{
    class Program
    {
        static void Main(string[] args)
        {            
            char grade = 'A'; /* local variable definition */

            switch (grade)
            {
                case 'A':
                    Console.WriteLine("Excellent!");
                    break;
                case 'B':
                case 'C':
                    Console.WriteLine("Well done");
                    break;
                case 'D':
                    Console.WriteLine("You passed");
                    break;
                case 'F':
                    Console.WriteLine("Better try again");
                    break;
                default:
                    Console.WriteLine("Invalid grade");
                    break;
            }
            Console.WriteLine("Your grade is  {0}", grade);
            Console.ReadLine();
        }
    }
}

Output:

C# Switch Statement example

 

3 - Using goto in a C# switch Statement

In the above section we used break to exit out of the switch statement. The result of this is to move the point of program execution to the statements immediately following the switch statement. Unfortunately this presents a problem when the default statements are also required to be executed. To address this requirement, we can replace the break statements with a goto default statement.

For Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FirstProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            string carModel;
            string carManufacturer = "unknown";

            Console.Write("Please Enter Your Vehicle Model: ");

            carModel = Console.ReadLine();

            switch (carModel)
            {
                case "Patriot":
                case "Liberty":
                case "Wrangler":
                    carManufacturer = "Jeep";
                    goto default;
                case "Focus":
                    carManufacturer = "Ford";
                    goto default;
                case "Corolla":
                    carManufacturer = "Toyota";
                    goto default;
                default:
                    Console.WriteLine("The " + carModel + " is manufactured by " + carManufacturer);
                    break;
            }
            Console.ReadLine();
        }
    }
}

Output:

Using goto in a C# switch Statement

 

4 - Using continue in a C# switch Statement

Another alternative to the break statement is the continue statement. If the switch statement is part of a loop, the continue statement will cause execution to return immediately to the beginning of the loop, bypassing any subsequent code yet to be executed in the current loop iteration.

 

5 - C# Switch Statement with Enum

In c#, we can use enum values with switch statements to perform required operations.

Example of using enum values in the c# switch case statement:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FirstProgram
{
    class Program
    {
        public enum location
        {
            loc_1,
            loc_2,
            loc_3
        }
        static void Main(string[] args)
        {
            location loc = location.loc_2;
            switch (loc)
            {
                case location.loc_2:
                    Console.WriteLine("Location: location_2");
                    break;
                case location.loc_3:
                    Console.WriteLine("Location: location_3");
                    break;
                case location.loc_1:
                    Console.WriteLine("Location: location_1");
                    break;
                default:
                    Console.WriteLine("Not Known");
                    break;
            }       
            Console.ReadLine();
        }   
    }
}

Output:

 C# Switch Case Statement with Enum

 

6 - C# Nested Switch Statement

It is possible to have a switch as part of the statement sequence of an outer switch. Even if the case constants of the inner and outer switch contain common values, no conflicts will arise.

Syntax:

The syntax for a nested switch statement is as follows:

switch(ch1) 
{
   case 'A':
   printf("This A is part of outer switch" );
   switch(ch2)
   {
      case 'A':
         printf("This A is part of inner switch" );
         break;
      case 'B': /* inner B case code */
   }
   break;
   case 'B': /* outer B case code */
}

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FirstProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 200;
            int b = 300;

            switch (a)
            {
                case 200:
                    Console.WriteLine("This is part of outer switch ");
                    switch (b)
                    {
                        case 300:
                            Console.WriteLine("This is part of inner switch ");
                            break;
                    }
                    break;
            }
            Console.WriteLine("Exact value of a is : {0}", a);
            Console.WriteLine("Exact value of b is : {0}", b);
            Console.ReadLine();
        }
    }
}

Output:

C# Nested Switch Statement Example

 

7 - Example of Switch Statement in C#

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FirstProgram
{
    class Program
    {
        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;
            }
            Console.ReadLine();
        }   
    }
}

Output:

Example of Switch Statement in C#