C# Switch Statement

C# offers switch statements which allow you to have multiple selections based on a constant value of a variable. A switch statement is equivalent to a multiple selections if statement but a switch statement is used if the variable to be compared has a constant value such as a number, a string, or a character. Constant values are values that don’t change. Below shows the syntax of a switch Statement c#.

switch (testVar)
{
case compareVal1:
code to execute if testVar == compareVa11;
break;
case compareVa12:
code to execute if testVar == compareVa12;
break;
.
.
.
case compareVa1N:
code to execute if testVer == compareVa1N;
break;
default:
code to execute if none of the values above match the testVar;
break;
}

You pass a variable to a switch statement. This variable is then compared to each case statement inside the block of the switch. If the variable matched a value in a case statement, the code of that particular case statement is executed. Note that even if the number of lines of code inside a case statement is more than one, we don’t use curly braces. The end of the body of a case statement is determined by the keyword break which brings the program outside of the switch statement and executes any code following the structure. If this is omitted, then you will encounter an error.

The switch statement also has a default statement which is executed if none of the values of all the case statements match the value of the test variable. The default statement is optional and nothing will happen if you remove it except that nothing will be executed if no values match the cases. The position of the default statement is not important, but it is a habit to place it below.

Let’s look at an example of how to use a switch statement.

using System;

namespace SwitchStatementDemo
{
    public class Program
    {
        public static void Main()
        {
            int choice;

            Console.WriteLine("What's your favorite pet?");
            Console.WriteLine("[1] Dog");
            Console.WriteLine("[2] Cat");
            Console.WriteLine("[3] Rabbit");
            Console.WriteLine("[4] Turtle");
            Console.WriteLine("[5] Fish");
            Console.WriteLine("[6] Not in the choices");
            Console.Write("\nEnter your choice: ");

            choice = Convert.ToInt32(Console.ReadLine());

            switch (choice)
            {
                case 1:
                    Console.WriteLine("Your favorite pet is Dog.");
                    break;
                case 2:
                    Console.WriteLine("Your favorite pet is Cat.");
                    break;
                case 3:
                    Console.WriteLine("Your favorite pet is Rabbit.");
                    break;
                case 4:
                    Console.WriteLine("Your favorite pet is Turtle.");
                    break;
                case 5:
                    Console.WriteLine("Your favorite pet is Fish.");
                    break;
                case 6:
                    Console.WriteLine("Your favorite pet is not in the choices.");
                    break;
                default:
                    Console.WriteLine("You don't have a favorite pet.");
                    break;
            }
        }
    }
}

Example 1 – Using a switch Statement

What's your favorite pet?
[1] Dog
[2] Cat
[3] Rabbit
[4] Turtle
[5] Fish
[6] Not in the choices

Enter your choice: 2
Your favorite pet is Cat.
What's your favorite pet?
[1] Dog
[2] Cat
[3] Rabbit
[4] Turtle
[5] Fish
[6] Not in the choices

Enter your choice: 99
You don't have a favorite pet.

The program above lets you pick what your favorite pet is. Each pet has been assigned a corresponding number. You enter that number and then it was compared inside the switch structure. If a matching number in a case statement is found, the appropriate message is shown. If none of the case statements match, then the default statement is executed.

Another feature of the switch statement is that you can make two or more case values to execute one set of codes. For example, what if you want values 1, 2, and 3 to execute one set of code? You simply write a case immediately after another.

switch(number)
{
    case 1:
    case 2:
    case 3:
       Console.WriteLine("This code is shared by three values.");
       break;
}

I said earlier that a switch statement is equivalent to a multiple selections if statement. So another way to write the program in Figure 1 is like this:

if (choice == 1)
   Console.WriteLine("Your favorite pet is Dog.");
else if (choice == 2)
   Console.WriteLine("Your favorite pet is Cat.");
else if (choice == 3)
   Console.WriteLine("Your favorite pet is Rabbit.");
else if (choice == 4)
   Console.WriteLine("Your favorite pet is Turtle.");
else if (choice == 5)
   Console.WriteLine("Your favorite pet is Fish.");
else if (choice == 6)
   Console.WriteLine("Your favorite pet is not in the choices.");
else
   Console.WriteLine("You don't have a favorite pet.");

The code above will have exactly the same result as the switch statement. Notice that the default statement is equivalent to the elsestatement. So what should you use between the two? We use switch statement if the value to be compared is constant or is not changing. So the below code is prohibited.

int myNumber = 5;
int x = 5;

switch (myNumber)
{
   case x:
      Console.WriteLine("Error, you can't use variables as a value" + 
                        " to be compared in a case statement.");
      break;
}

You can see here that even though x has a value of 5 which obviously matches the value of the test variable myNumber, an error occurred because x is not constant, or to say it in other words, it has a possibility of changing its value. If you want to use x and yield no error, you have to make it a constant variable.

int myNumber = 5;
const int x = 5;

switch (myNumber)
{
   case x:
      Console.WriteLine("Error has been fixed!");
      break;
}

We used the const keyword to make the value constant. Note that after declaring a variable as constant, you won’t be able to change its value anywhere in a program. Also, note that you need to supply a value in the declaration of a constant variable. A switch statement must match a value of the test variable to the case value so you cannot test if a test variable is less than or greater than the other value. For example, there is no such thing as this:

switch (myNumber)
{
   case x > myNumber:
      Console.WriteLine("switch statements can't test if a value is less than " +
                        "or greater than the other value.");
      break;
}

Therefore, it is harder to test if the test value is equal to a range of values. This time, you have to use the multiple selection if statement because you will have a hard time if you stick with switch statements.