Skip to content

C# - Switch

In C#, the switch construct provides a clean way to control program flow based on the value of a variable or expression. It allows you to execute different blocks of code by comparing a value against a list of possible cases. Modern C# offers two forms: the traditional switch statement and the more concise switch expression.

The switch statement is a control-flow statement that executes code associated with a matching case label.

switch (expression)
{
case constant_value1:
// Code to execute
break; // Exits the switch
case constant_value2:
// Code to execute
break;
// You can have any number of case statements
default: // Optional
// Code to execute if no other case matches
break;
}
  • Expression Type: The expression in a switch statement can be of an integral type (int, char, byte…), a string, an enum, or, with modern C#, any type thanks to pattern matching.
  • break is Required: Each non-empty case block must end with a jump statement, most commonly break. This prevents accidental “fall-through,” which is a common source of bugs in other languages like C++.
  • Fall-Through for Empty Cases: You can stack case labels to execute the same code for multiple values. The compiler allows fall-through only from an empty case.
  • default Case: The optional default case executes if none of the other case expressions match the switch expression. It can be placed anywhere in the switch block, but is conventionally last.
  1. The switch expression is evaluated once.
  2. The program control jumps to the case label whose constant value matches the result of the expression.
  3. The code within that case block is executed until a break statement is encountered.
  4. If a break is hit, control jumps to the first statement after the switch block.
  5. If no case label matches, control jumps to the default block (if one exists).
using System;
char grade = 'B';
string feedback;
switch (grade)
{
case 'A':
feedback = "Excellent!";
break;
case 'B':
case 'C':
feedback = "Well done.";
break;
case 'D':
feedback = "You passed.";
break;
case 'F':
feedback = "Better try again.";
break;
default:
feedback = "Invalid grade.";
break;
}
Console.WriteLine($"Feedback for grade {grade}: {feedback}");
// Output: Feedback for grade B: Well done.

Modern C#: switch Expressions (C# 8.0 and later)

Section titled “Modern C#: switch Expressions (C# 8.0 and later)”

The switch expression provides a more concise, functional syntax. Instead of being a statement that controls flow, it’s an expression that returns a value.

var result = variableToSwitchOn switch
{
pattern1 => expression1,
pattern2 => expression2,
_ => defaultExpression // _ is the discard pattern, equivalent to default
};

The previous example can be rewritten far more elegantly:

using System;
char grade = 'B';
string feedback = grade switch
{
'A' => "Excellent!",
'B' or 'C' => "Well done.", // 'or' pattern for multiple values
'D' => "You passed.",
'F' => "Better try again.",
_ => "Invalid grade."
};
Console.WriteLine($"Feedback for grade {grade}: {feedback}");
// Output: Feedback for grade B: Well done.

Modern switch statements and expressions support pattern matching, which lets you switch on an object’s properties, type, or other characteristics, not just constant values.

Imagine calculating shipping costs based on the destination and order total. A switch expression with property patterns is perfect for this.

public record Order(decimal Total, string DestinationCountry);
public decimal CalculateShipping(Order order)
{
return order switch
{
// Property Pattern: checks properties of the order object
{ DestinationCountry: "USA" } => 5.00m,
// Property Pattern with a when clause for additional logic
{ DestinationCountry: "EU", Total: > 100.0m } => 0.00m, // Free shipping for EU orders over 100
{ DestinationCountry: "EU" } => 10.00m,
// Discard Pattern: catches all other cases
_ => 20.00m // International shipping
};
}
// Usage:
var myOrder = new Order(150.0m, "EU");
Console.WriteLine($"Shipping cost: {CalculateShipping(myOrder):C}");
// Output: Shipping cost: $0.00
  • Use if-else if for simple boolean conditions or a small number of checks.
  • Use a switch statement when you need to execute different blocks of statements (multiple lines of code) based on a value and don’t need to return a result directly.
  • Use a switch expression when you need to produce a single value based on a set of conditions. It’s more concise and less error-prone.