Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Returning Values from a C# Switch Expression

Learn how C# switch expressions produce values directly, with syntax, pattern matching examples, and practical guidance on choosing between a switch expression and a switch statement.

~8 min readC#
#C# switch expressions#Return values#C# patterns#Switch expression
Illustration of a C# switch expression mapping an input to a return value, with arrows indicating pattern matching branches.

When you need to return a value from a switch expression, place the input expression before the switch keyword and map each pattern to a result with =>. A switch expression is an expression rather than a statement, so it evaluates to a value and can be assigned to a variable, returned from a method, passed as an argument, or used in a lambda body. This article covers the syntax, common patterns, edge cases, and when a switch expression is a better choice than a classic switch statement.

Syntax of a Switch Expression

A switch expression uses the switch keyword and arrow (=>) separators between each arm and its result. The expression evaluates to one of the arm values. Here is the minimal syntax:

csharp
int GetPriority(string level) { return level switch { "low" => 1, "medium" => 2, "high" => 3, _ => 0 }; }

The input expression (here level) appears before the switch keyword. Each arm consists of a pattern, followed by =>, followed by the value or expression to return. The underscore (_) is the discard pattern, which acts as the default case. The entire switch expression is terminated by a semicolon after the closing brace.

Unlike a switch statement, a switch expression has no break or return inside the arms and does not use a default: label; the discard pattern (_) serves as the fallback. Each arm has a result expression, and the whole expression is usually assigned or returned. A throw expression is also allowed in an arm, in which case the switch expression throws instead of producing a value. Because the arms are expressions, there is no fall-through from one arm to the next, so a missing break cannot be a bug.

Returning Values from Methods

Switch expressions are particularly useful when you need to map an input to a result in a single expression. Consider a method that returns a text representation based on an enum value:

csharp
public string GetStatusMessage(OrderStatus status) { return status switch { OrderStatus.Pending => "Order is pending.", OrderStatus.Shipped => "Order has shipped.", OrderStatus.Delivered => "Order delivered.", OrderStatus.Cancelled => "Order cancelled.", _ => "Unknown status." }; }

Because the switch expression is an expression, it can also be used directly in an assignment, a function argument, or a lambda body. This reduces boilerplate and keeps the logic declarative. The compiler can also analyze the possible patterns and warn if not all possible inputs are covered by a pattern, prompting developers to add a discard pattern.

Pattern Matching in Switch Expressions

Switch expressions support C# pattern matching beyond constant patterns, including type patterns, property patterns, and—starting in C# 9—relational patterns. These patterns make the expression more expressive and reduce the need for nested if-else chains.

Type Pattern Example

Suppose you have a method that processes a shape and returns its area. Using a switch expression with type patterns:

csharp
public double GetArea(Shape shape) { return shape switch { Circle c => Math.PI * c.Radius * c.Radius, Rectangle r => r.Width * r.Height, Triangle t => (t.BaseLength * t.Height) / 2, _ => throw new ArgumentException($"Unknown shape: {shape.GetType().Name}") }; }

In this example, each arm matches a specific type and then uses the variable (e.g., c, r, t) to access properties. The discard pattern throws an exception instead of returning a value, illustrating that the expression can contain any expression on the right side of =>, including throw.

Relational Pattern Example

Relational patterns allow comparisons using <, >, <=, >=. For example, classify a temperature score:

csharp
public string ClassifyTemperature(int celsius) { return celsius switch { <= -10 => "Very cold", < 0 => "Cold", < 15 => "Mild", < 25 => "Warm", _ => "Hot" }; }

The patterns are evaluated in order, and the first matching arm produces the value. The discard pattern catches any remaining input, ensuring a return value exists.

Relational patterns require C# 9 or later, so this example needs a LangVersion of 9.0 or higher.

When the Input Is a Collection or Multiple Values

Switch expressions can also evaluate tuples, which is useful when a decision depends on multiple inputs. For example, determine a color based on two boolean flags:

csharp
public string GetColor(bool isPrimary, bool isDark) { return (isPrimary, isDark) switch { (true, true) => "Dark primary", (true, false) => "Light primary", (false, true) => "Dark secondary", (false, false) => "Light secondary" }; }

The left side of the switch is a tuple literal. Each arm uses a positional pattern that matches the tuple's elements. This approach avoids nested conditionals and is more readable than a series of if statements.

Common Pitfalls: Return Type Consistency

One of the most frequent mistakes is having arms that return values of different types. The compiler infers a common type for the entire expression, and if the types do not have a common type, compilation fails. For example:

csharp
object GetValue(bool flag) { return flag switch { true => "text", // string false => 42 // int }; }

This code compiles because the target type is object, and there is an implicit conversion from both string and int to object. However, if the method's return type is int, the arm with the string would cause a compilation error. The rule is that every arm must be implicitly convertible to a common type, typically the target type of the expression.

Another pitfall is forgetting that the discard pattern is only optional when the compiler can prove exhaustiveness. For reference types, that proof often depends on null-state analysis, so handle a possible null with a null pattern or with a discard arm that covers the remaining cases. With nullable reference types enabled, the compiler can flag code where a null input would slip through a set of non-null patterns.

Performance Considerations

The runtime cost of a switch expression is generally the same as the equivalent switch statement. The compiler can emit efficient jump tables or a series of comparisons, depending on the patterns. However, you should not assume that a switch expression is always faster than an if chain; it depends on the complexity of the patterns and the JIT's optimization. In most production scenarios, the readability and maintenance benefits outweigh any micro-optimization differences.

One relevant performance aspect is the allocation of boxed values or delegates if the arms involve conversions. For example, if the method returns object and each arm creates a new value type, boxing occurs. But this is identical to what happens with a switch statement.

For CPU-bound paths where the switch expression is called millions of times, you might measure the generated IL to confirm no unexpected allocations. In practice, the JIT treats switch expressions similarly to switch statements, so the primary cost is often the pattern evaluation itself, especially with complex property patterns. If you notice hotspots, use benchmark tools to guide the decision, but do not prematurely rewrite code based on speculative performance.

Maintainability and Why It Matters

Switch expressions contribute to maintainability because they keep the mapping between input and output in a single place, making it easier to add or remove cases. With a classic switch statement, each non-empty section must end with break, return, throw, or goto; a missing jump statement is a compile error rather than silent fall-through, but the extra boilerplate can make the mapping harder to scan. A switch expression removes that scaffolding by design.

Consider the evolution of an order status handler. Adding a new status in a switch expression requires adding one arm; the compiler then warns you if the set of patterns is not exhaustive. That early feedback is valuable, especially when the input is an enum with a finite set of values.

However, a switch expression is not always the best choice. If the logic inside each case is complex—involving many statements, variable declarations, or side effects—a switch statement is clearer. The expression form is best suited for mapping inputs to outputs, not for executing blocks of code. For example, if each case involves logging multiple lines and updating several fields, a standard switch statement reads better.

Another maintainability concern is readability when the patterns get nested. Long chains like (x, y) switch { (0, 0) => ... } are fine for a small set of tuples, but if the input has many fields, consider using a property pattern or a dedicated method. Overly complex expressions can hurt readability, and a well-named method with a switch statement may be preferable.

Choosing Between Switch Statement and Switch Expression

The decision between a switch statement and a switch expression hinges on the shape of the logic. Use a switch expression when the code maps an input to a value and each arm produces a single expression. Use a switch statement when each case requires multiple statements, local scoped variables, or a sequence of operations with control flow (like break or goto).

ConcernSwitch expressionSwitch statement
Produces a valueYes, directlyRequires return or assignment
Fall-through behaviorNo fall-through between armsSections must end with break, return, throw, or goto; implicit fall-through is not allowed
Complex per-case logicAwkwardSuitable
Exhaustiveness checkCompiler warning for missing patternsNo automatic check
Best forMapping inputs to outputsMulti-step processing per case

A switch expression is more concise, but it is not inherently more performant. The choice should be driven by clarity and maintainability, not by assumptions about efficiency.

Advanced Usage: Property and Var Patterns

Beyond constant and type patterns, switch expressions support property patterns that allow you to match on an object's properties directly. For example, classify a point:

csharp
public string ClassifyPoint(Point point) { return point switch { { X: 0, Y: 0 } => "Origin", { X: 0 } => "On Y-axis", { Y: 0 } => "On X-axis", _ => "In quadrant" }; }

The property pattern checks whether point.X equals 0 and point.Y equals 0, and so on. This can replace nested if checks with a single, readable expression.

Var patterns are also useful when you want to bind the matched value to a new variable without actually testing its type—essentially a fallback that captures the value. For instance:

csharp
public string Describe(object obj) { return obj switch { null => "null", int i when i > 10 => "Big integer", string s => $"String of length {s.Length}", var other => $"Unknown type: {other.GetType().Name}" }; }

The var other pattern matches any value and binds it to other for use in the arm. It is similar to the discard pattern in terms of matching, but it lets you reference the captured value, which the discard pattern does not. Because var also matches null, the example above handles null explicitly before reaching the var arm.

Compatibility and Language Version Dependencies

Switch expressions were introduced in C# 8.0 and have been refined in later versions. The basic constant, type, property, and var pattern examples in this article compile with C# 8. The relational pattern example earlier (<= -10, < 0) requires C# 9 or later. If your project uses an earlier language version, you cannot use these features without raising LangVersion: set at least 8.0 for switch expressions, and at least 9.0 for relational patterns. .NET Core 3.x and .NET 5+ support switch expressions natively, but if you are targeting the .NET Framework, you need C# 8.0 support through the Roslyn compiler, and you must use the .NET Core SDK or a compatible compiler. Always verify the target framework's compatibility when adopting switch expressions.

Additionally, the behavior of null handling changed with nullable reference types. When the input is a reference type, ensure you handle null explicitly if the compiler's null-state analysis requires it. Use the null pattern or a discard pattern that covers null. For example:

csharp
public string GetOrDefault(string? value) { return value switch { null => "default", _ => value }; }

This code explicitly handles a null input, avoiding a null reference exception if the null pattern were omitted.

Switch expressions are a powerful tool for producing return values concisely, but they are most effective when the logic fits the expression form. As with any language feature, the best choice depends on the specific code structure and the maintainability tradeoffs that matter for your team.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.