C# switch

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.

Switch Syntax

The general structure of the switch statement is:

  • The keyword switch starts the structure, followed by a variable (or switch expression) enclosed in parentheses. Expression can be of any type including string, integer, bool, char, enum, etc.
  • 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.

C# Switch Statement Syntax

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

Switch Flowchart

C# Switch Flowchart

C# Switch Without Default Label

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.

C# Switch without Default Label

Test Code

OUTPUT

Case Two

C# Switch with Default Label

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.”

C# Switch with Default Label

Test Code

OUTPUT

No matching case found.

C# Switch with Enum

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.

C# Switch with Enum

Test Code

OUTPUT

Two & Three

C# Switch with String

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;
}

Test Code

OUTPUT

Subtracting…

C# Switch with goto 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:

C# Switch with goto Statement

Test Code

OUTPUT

B

C# Switch with return 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;
        }
    }
}

Test Code

OUTPUT

103

C# Switch Fall Through

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.

C# Switch Fall Through

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

Test Code

OUTPUT

Case two, three, and four

Nested Switch Statements

A 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;
}

Test Code

OUTPUT

C#
Intermediate C# Tutorials

C# Switch with const

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;
}

Test Code

OUTPUT

Case : 3

C# Switch 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.

Community Input

💬 What other C# Switch topics should I cover here?

Please use twitter or instagram to share your suggestions. We will add your feedback here.

Share Love ❤️

Like this on Instagram

Like this on twitter

Resources

  1. switch
  2. Break
  3. Goto
  4. Return
Sending
User Rating 0 (0 vote)

TidBits