Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

C# if vs switch: Choosing the Right Branching Construct

Understand when to use an if-else chain vs a switch statement in C#. Compare syntax, pattern matching, performance, and maintainability.

~5 min readC#
#C##switch statement#if-else#pattern matching
A visual comparison of C# if-else and switch branching constructs, showing a decision path and a switch-like selection.

When you need to branch on a value in C#, you have two primary options: if-else chains and switch statements. The choice between them affects readability, maintainability, and sometimes performance. This article compares the two constructs and explains when each is the better fit.

Syntax Differences Between if-else and switch

The most obvious difference is syntax. An if-else chain evaluates a boolean expression and executes the first block whose condition is true. A switch statement evaluates a single expression and compares it against a set of cases, which can be constant values or more complex patterns.

csharp
// if-else int statusCode = GetStatusCode(); if (statusCode == 200) { Console.WriteLine("OK"); } else if (statusCode == 404) { Console.WriteLine("Not Found"); } else { Console.WriteLine("Other"); } // switch statement switch (statusCode) { case 200: Console.WriteLine("OK"); break; case 404: Console.WriteLine("Not Found"); break; default: Console.WriteLine("Other"); break; }

The switch statement requires a break (or another jump statement) at the end of each non-empty case to prevent fallthrough. This is a common source of errors for developers new to C#, but it also makes the control flow explicit.

Since C# 8, switch expressions offer a more concise form:

csharp
string result = statusCode switch { 200 => "OK", 404 => "Not Found", _ => "Other" };

Switch expressions are expression-based and can be used directly in assignments or return statements. They eliminate the need for break and reduce boilerplate.

Pattern Matching in switch

Modern C# switch statements and expressions support pattern matching, which goes far beyond simple constant equality. You can match on types, relational patterns, property patterns, and more.

csharp
object value = GetValue(); string description = value switch { int i when i > 0 => $"Positive integer {i}", int i => $"Non-positive integer {i}", string s => $"String of length {s.Length}", _ => "Unknown type" };

This makes switch a powerful tool for type-based dispatch, something that would require a long if-else chain with is checks and casts. If you find yourself writing if (x is TypeA) ... else if (x is TypeB) ..., a switch with type patterns is usually cleaner.

Performance: Compiler and Runtime Behavior

Performance differences between if-else and switch depend on the number of cases and the type of the expression. For a small number of cases, the generated code is often similar. For a larger set of integer or enum cases, the runtime may generate a jump table, which allows constant-time dispatch. An if-else chain normally evaluates conditions sequentially, so the worst-case cost grows linearly with the number of branches.

However, modern CPUs and branch predictors make this distinction less significant in many real-world scenarios. Compiler and JIT optimizations can also vary by .NET version and code shape, so avoid assuming one construct is always faster. If performance matters, profile the specific code path. In most application code, readability and maintainability outweigh micro-optimizations.

Maintainability and Readability

Readability is where the choice often matters most. A switch statement clearly signals that you are selecting based on one value. An if-else chain can express complex boolean logic that switch cannot.

csharp
if (user.IsActive && user.Role == "Admin" || user.IsSuperUser) { // complex condition }

Switch cannot handle such compound conditions directly; you would need to use a when clause for each case, but that becomes unwieldy. For simple equality checks against constants, switch is more concise and easier to scan. For range checks that are part of larger boolean expressions, null checks, or conditions that combine multiple variables, if-else is often the natural fit.

Another maintainability factor is the risk of missing a case. With a classic switch statement, analyzers can warn about incomplete switches on enums; switch expressions add exhaustiveness checking. If-else chains have no such safety net. Conversely, adding a new branch to an if-else chain is straightforward, while switch cases require careful placement and break statements.

Common Pitfalls and Edge Cases

Fallthrough is the classic switch pitfall. C# does not allow implicit fallthrough from one non-empty case to another. You must use break, return, goto, or throw. This prevents accidental fallthrough but can lead to verbose code if you want to share logic between cases. You can stack labels to share a body:

csharp
switch (color) { case "red": case "blue": Console.WriteLine("Primary color"); break; default: Console.WriteLine("Other"); break; }

If-else chains avoid fallthrough, but deeply nested conditions can become hard to scan. Also, switch expressions must be exhaustive; if the compiler cannot prove that all possible values are covered, you need a discard pattern _. If-else chains do not have an exhaustiveness requirement, which can be both a benefit and a risk.

Decision Criteria: When to Use if vs switch

The decision should be based on the structure of the condition and the number of branches.

Use a switch statement or expression when:

  • You are comparing a single expression against a fixed set of constants (integers, strings, enums).
  • You need pattern matching on types or properties.
  • The number of cases is more than three or four, and the logic for each case is short.
  • You want exhaustiveness checking for enum values (available with switch expressions or analyzer warnings).

Use an if-else chain when:

  • The condition involves multiple variables or boolean operators (&&, ||, !).
  • You need to test ranges or boundary conditions that are clearer as comparison expressions.
  • The branches have different complexity and some require early returns or complex logic.
  • You are checking for null or other non-constant conditions.

In practice, many codebases use both. A common pattern is to use switch for dispatch based on a type or enum, and if-else for validation logic that combines multiple checks.

Advanced: Switch Expressions and Recursive Patterns

Switch expressions become particularly powerful when combined with recursive patterns. For example, you can deconstruct a tuple or a record and match on its components:

csharp
var point = (X: 3, Y: 4); string quadrant = point switch { ( > 0, > 0) => "Q1", ( < 0, > 0) => "Q2", ( < 0, < 0) => "Q3", ( > 0, < 0) => "Q4", _ => "On axis" };

This kind of pattern would be verbose and error-prone with if-else. If you find yourself writing nested if-else to inspect fields or properties, switch expressions with positional or property patterns are often clearer. Switch expressions require C# 8 or later. The relational pattern syntax used in the tuple example requires C# 9 or later. Older default language versions may not include these features, so you might use the classic switch statement instead.

Compiler and Runtime Optimizations

One often-overlooked aspect is that the C# compiler and the just-in-time (JIT) compiler can optimize both constructs. For example, a switch on a string can be implemented as a hash-based lookup, while an if-else chain of string comparisons normally evaluates each comparison in sequence. Similarly, a switch on an enum can be optimized to a jump table, whereas an if-else chain is a series of comparisons. These optimizations are implementation details and can change between .NET versions. If you are writing performance-sensitive code, measure with a profiler rather than assuming one construct is always faster.

The choice between these constructs should ultimately be driven by the readability and maintainability of the code you are writing. In most business applications, the performance difference is negligible, and clarity of control flow is what matters. Use switch when it makes the intent obvious, and use if-else when the logic is genuinely conditional.

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.