C# Basics

C# switch Statement

Table of Contents

The switch Statement

C# switch statement is a control statement that tests a single expression against a list of multiple cases. It then compares the value received from the switch expression against the value of each of the cases. Every switch case must end with the break keyword or goto case keyword or an empty block.

C# switch may result in cleaner code than multiple if statements since switch statements require an expression to be compared only once.

By the end of this article, you’ll know:

  • What switch is and how to write a switch statement
  • How the switch statement works
  • How to use switch statement with default case (optional)
  • How to use switch with enumeration data type
  • How to use strings in switch expressions, and string literals in case labels.
  • How to use goto keyword to jump to a new location in the code
  • How to use grouped cases to execute same structure in more than one case
  • How to put a switch statement inside a switch statement

Let’s get started!

Watch Now High-Definition Instructional Video: C# switch Statement
Edit, and test all the CODE examples used in this article with C# online editor:  Code Playground

Syntax

The general structure of the switch is:

C# Switch Statement Syntax
  • The keyword switch starts the structure, followed by a variable (or switch expression) enclosed in parentheses. Expression can be of any built-in integral types; the boolchar, and enum types; and the string type.
  • The keyword case follows one of the possible values that represent the values of the switch expression and then a colon “:” at the end. When the switch expression finds the matching value specified by a case label, it executes the statements inside that case.
  • The keyword break causes a bypass of the rest of the switch and resumes with the first statement after the closing curly brace of the switch structure.
  • The keyword default is optional, which executes if none of the other cases matches the value specified by the switch expression.

Note: The values used in each case clause must be constants, not variables or expressions containing variables.

C# switch Statement Example

Flowchart

Switch Statement Flowchart

C# switch Statement Example

You can have as many cases as you want in whatever sequence possible when using a switch statement.

In the following example, the value of intValue variable is 2. After executing the code, the case label 2 matches the value provided by the switch expression, hence it executes the statement within its block.

Example: C# switch Statement

Output

Case Two


The default Label With switch Statement

You can have as many cases as you want in whatever sequence possible when using a switch statement. The default case is optional, which executes if the switch value doesn’t match any of the cases available. It’s also a good practice to include the default label last for easy reading.

In the following example, the value of an intValue variable is 4. The switch statement compares this value with the case labels. If there’s a match, then statements inside that case block executes and the switch statement terminates; otherwise, the default case executes, which prints out “No matching case found.”

The default Label With switch Statement

Output

No matching case found.


The enum Keyword With switch Statement

Using an enumeration data type with a switch structure is also possible. C# enum keyword allows you to define a custom set of strongly typed name-value pairs. Consider the following code example, which performs a switch test on the Numbers enum. This is how you can use enumeration values in a switch structure.

Note: You need to define enum data type directly inside a namespace or a class.

The enum Keyword With switch Statement

Output

Two & Three


The goto Keyword With switch Statement

You can use goto keyword followed by a case label and a semicolon (;) at the end which will cause the execution to jump to a new location in the code. The target location defines the marker in the code, called a label. Consider the example given below:

The goto Keyword With switch Statement

Output

B


The return Keyword With switch Statement

You can use the return statement to exit from the current function containing the switch statement.

When the return statement is encountered, program execution returns to the calling code immediately. No lines of code after this statement are executed.

using System;
using System.Collections.Generic;

public class Program
{
  public static void Main()
  {
      int returnedValue = GetValue(2);
      Console.WriteLine(returnedValue);
  }

  static int GetValue(int returnValue)
    {
        switch (returnValue)
        {
          case 0:
              return 101;
          case 1:
              return 102;
          case 2:
              return 103;
          default:
              return 104;
        }
    }
}

Output

103


The const Keyword With switch Statement

The following example illustrates the use of a const as a case parameter, but it also shows that expressions are allowed as case parameters if the operands within the expression are constants.

const int constValue = 1;
int intValue = 3;

switch (intValue)
{
  case constValue:
    Console.WriteLine($"Case : {constValue}");
    break;
  case constValue + 1:
    Console.WriteLine($"Case : {constValue + 1}");
    break;
  case constValue + 2:
    Console.WriteLine($"Case : {constValue + 2}");
    break;
  default:
    Console.WriteLine("Invalid Value");
    break;
}

Output

Case : 3


The string Literals With switch Statement

One nice feature of the C# switch statement is that you can use string to control the selection of the cases. You use strings in switch expressions, and string literals in case labels.

string command = "-";
switch (command)
{
  case "+":
      Console.WriteLine("Adding...");
      break;
  case "-":
      Console.WriteLine("Subtracting...");
      // do_something_here();
      break;
  case "*":
      Console.WriteLine("Multiplying...");
      break;
  default:
      Console.WriteLine("Invalid Command");
      break;
}

Output

Subtracting…


Grouped Cases With switch Statement

If there are multiple cases with no statements in between, code execution will fall through to the next case block that contains code. Using multiple labels is appropriate, when you want to execute the same structure in more than one case (no need for goto statements).

In the following example, if the integerValue variable equals 2, the code in case 4 will execute because the case labels 2 and 3 are empty. If a case block is not empty, a break must be present before the next case label; Otherwise, the compiler will generate an error.

Grouped Cases With switch Statement

Note: Multiple case labels can be grouped together under a single switch section.

Output

Case two, three, and four

Here is another example, if the number equals 1, the code in case 2 executes because the case label 1 and 2 are grouped.

switch Statement with Grouped Cases example

Output

Case: One and Two


Nested switch Statements

C# switch statement can be created within another switch statement. This gives you a nested switch. Here is an example:

string language = "C#";
int level = 2;

switch (language)
{
  case "Python":
    Console.WriteLine("Python");
    break;
  case "C#":
    Console.WriteLine("C#");
    
    switch (level)
    {
      case 1:
        Console.WriteLine("Basic C# Tutorials");
        break;
      case 2:
        Console.WriteLine("Intermediate C# Tutorials");
        break;
      case 3:
        Console.WriteLine("Advanced C# Tutorials");
        break;
    }

    break;
  case "Java":
    Console.WriteLine("Java");
    break;
}

Output

C#
Intermediate C# Tutorials


Video: C# switch Statement


Good Practices

  • It’s better to use default statement at the end of the structure for easy reading.
  • Always use a default block to display error messages if none of the case statements matched.
  • Arrange them in ascending order if case label values are of integer type.
  • Sort them alphabetically if case label values are of character type.
  • It’s better to use fall-through in the switch statement to avoid code repetition. The code that evaluates to the same result.
  • You can use the goto keyword to jump to another case or a label.