Code has been added to clipboard!

How to Use C# Switch for Matching Expressions Against Multiple Cases

Reading time 3 min
Published Sep 17, 2019
Updated Oct 3, 2019

TL;DR – C# switch statement is for comparing a specific condition against three or more possible cases.

Principles of the switch Statement

C# switch is a selection statement for choosing a switch section matching the specified pattern. In other words, this statement tests whether a match expression equals any of the enumerated cases.

Tip: the match expression refers to the expression to be checked. Each condition is referred to as the C# switch case. The keyword case defines a statement. The value after the statement is a label.

Here is an illustration of the structure of the C# switch statement:

The following code example shows the use of the C# switch statement. Our code presents three possible cases, depending on the way people answer a question:

Example
using System;

public class Example
{
  public static void Main()
  {
    char answers = 'K';
    switch (answers)
    {
      case 'N':
        Console.WriteLine("Not pleased with the current services.");
        break;
      case 'Y':
        Console.WriteLine("Pleased with the current services.");
        break;
      case 'E':
        Console.WriteLine("No answer to this question.");
        break;
      default:
        Console.WriteLine("Invalid answer.");
        break;
    }
  }
}

The presented expression is N, and it corresponds to the Case 'N', meaning that the console will print the appropriate phrase.

Tip: the keyword break exits the case section. Be sure to include it for better functionality.

Additionally, you can include a default case for when the match expression does not match any of the other C# switch cases:

Example
using System;

public class Example
{
  public static void Main()
  {
    char answers = 'K';
    switch (answers)
    {
      case 'N':
        Console.WriteLine("Not pleased with the current services.");
        break;
      case 'Y':
        Console.WriteLine("Pleased with the current services.");
        break;
      case 'E':
        Console.WriteLine("No answer to this question.");
        break;
      default:
        Console.WriteLine("Invalid answer.");
        break;
    }
  }
}

Remember: single switch statement can only have one default case.

In this C# switch example, we generate a random match expression from the specified desserts. Then, the switch statement delivers the corresponding case and its label to the console:

Example
using System;

public enum Dessert
{
  Cake,
  Milkshake,
  Candy
}

public class Example
{
    public static void Main()
    {
        Dessert d = (Dessert)(new Random()).Next(0, 4);
        switch (d)
        {
          case Dessert.Cake:
            Console.WriteLine("The dessert is a cake");
            break;
          case Dessert.Milkshake:
            Console.WriteLine("The dessert is a milkshake");
            break;
          case Dessert.Candy:
            Console.WriteLine("The dessert is a candy");
            break;
          default:
            Console.WriteLine("No dessert for you");
          break;
      }
    }
}

Governing Types

The switch expression determines the governing type for the entire switch statement C#:

  • When the switch expression is sbyte, byte, short, int, ushort, uint, long, ulong, bool, char, string, enum_type, then that type becomes the governing type of the statement. The same applies to nullable types related to the mentioned types.
  • In other cases, a conversion from the switch expression type to one of the possible governing types must occur (or to a nullable type).
  • If a conversion does not take place or if multiple conversions occur, the compiler generates an error.

The governing type of a switch statement can be a string. This C# switch example illustrates this:

Example
using System;

public class Example
{
    public static void Main()
    {
      string str = "Yes, I have";
      switch (str)
      {
        case "Yes, I have":
          Console.WriteLine("The person has participated in this activity.");
          break;
        case "No, I have not":
          Console.WriteLine("The person has not participated in this activity.");
          break;
        case "I don't know":
          Console.WriteLine("The person does not know.");
          break;
        default:
          Console.WriteLine("The person did not respond.");
          break;
      }
   }
}

In this example of C# switch string type, we reveal how to make the match expression as a string.

Note: switch C# cannot have duplicate cases. Otherwise, compilers show an error.

The switch Statement and Patterns

Before the release of C# 7.0, it was necessary to define value and check it against the specified cases. After the new version was released, the switch statement C# allows comparing the value of switch with the value delivered by an expression, not the fixed value.

Example
using System;

public class Example
{
    public static void Main()
    {
        Console.WriteLine("Available hotel rooms: 1=one room apartament 2=two room apartament 3=three room apartament");
        Console.Write("Please choose your hotel room: ");
        string str = Console.ReadLine();
        int cost = 0;
        // Due to the goto statements in 2 and 3 cases, the base cost
        // cents is added to the additional cost for the two-room and three-room apartments.
        switch (str)
        {
            case "1":
            case "one room apartament":
                cost += 15;
                break;
            case "2":
            case "two room apartament":
                cost += 15;
                goto case "1";
            case "3":
            case "three room apartament":
                cost += 15;
                goto case "2";
            default:
                Console.WriteLine("Invalid selection. Please select 1, 2, or 3 and try again.");
                break;
        }

        if (cost != 0)
        {
            Console.WriteLine("You need to pay {0} dollars.", cost);
        }

        Console.WriteLine("Thank you for booking in our hotel!");
    }
}

Every switch case C# specifies a condition or a statement which is compared to the match expression. Once it finds a match, the switch section is executed. This feature is available in all versions from C# 7.0.

C# switch: Useful Tips

  • If you are testing an expression against two cases, you should apply if-else statement instead.
  • If the C# switch does not have a default case, then the code won’t be executed when there are no matches.
  • Since C# does not permit the code to run from one case label to another, you have to use break. However, this is not the only option. Consider goto or return.
C# Switch
C# List
C# Array
C# Enum
Discord Bot
Redirect Types
MongoDB Tutorial
Java Version Check
XML Formatter