C# switch Statement

The C# switch statement works similar to if-else ladder, it's often used as an alternative of if-else construct. The switch statement is also called selection statement. It selects one statement to execute from a list of statements.

Following is the syntax of a C# switch statement.

switch(expression) 
{
   case constant-expression  :
      statement(s);
      break; /* optional */
	
   case constant-expression  :
      statement(s);
      break; /* optional */

   default : /* Optional */
}

Let's understand switch statement flow with an image.

In the previous section, we have created an if-else ladder to check the value the a. Let's create the similar example using a switch statement. Following C# switch example checks the value of a. If the value lies between 0-5 it prints its string value. It prints a message The value is not defined in the switch statement in case value does not match with any case.

Example

Try It
using System;
 
namespace TutorialsLeader
{
    public class MyFirstClass
    {
        static void Main()
        {
            int a = 2;
 
            switch (a)
            {
                case 0:
                    Console.WriteLine("The value of a is zero");
                    break;
                case 1:
                    Console.WriteLine("The value of a is one");
                    break;
                case 2:
                    Console.WriteLine("The value of a is two");
                    break;
                case 3:
                    Console.WriteLine("The value of a is three");
                    break;
                case 4:
                    Console.WriteLine("The value of a is four");
                    break;
                case 5:
                    Console.WriteLine("The value of a is five");
                    break;
                default:
                    Console.WriteLine("The value is not defined in the switch statement");
                    break;
            }
        }
    }
}

Match Expression

Match expression switch (expr) is an important part of switch statemant. A Match expression must return the value of following types.

  • a char
  • a string
  • a bool
  • an integral value, such as an int or a long
  • an enum value

Let's learn about the do-while loop in C# in the next section.