0
0
C Sharp (C#)programming~15 mins

Switch expression (modern C#) - Deep Dive

Choose your learning style9 modes available
Overview - Switch expression (modern C#)
What is it?
A switch expression in modern C# is a concise way to choose a value based on matching patterns or cases. Instead of writing long switch statements with many lines, switch expressions let you write the logic in a compact, readable form. They return a value directly and can handle complex matching with simple syntax.
Why it matters
Switch expressions make code easier to read and write by reducing boilerplate and nesting. Without them, developers write longer, more error-prone switch statements that are harder to maintain. This feature helps create clearer decision-making code, improving productivity and reducing bugs.
Where it fits
Before learning switch expressions, you should understand basic C# syntax, variables, and traditional switch statements. After mastering switch expressions, you can explore pattern matching, expression-bodied members, and functional programming styles in C#.
Mental Model
Core Idea
A switch expression is a compact way to pick a value by matching a variable against patterns, returning the result directly.
Think of it like...
It's like choosing a flavor of ice cream by quickly pointing to the right scoop instead of asking a long list of questions.
Input Value
   │
   ▼
┌───────────────┐
│ Switch Expr   │
│ ┌───────────┐ │
│ │ Pattern 1 │ ├─► Result 1
│ │ Pattern 2 │ ├─► Result 2
│ │   ...     │ │
│ │ Pattern N │ ├─► Result N
│ └───────────┘ │
└───────────────┘
Build-Up - 6 Steps
1
FoundationUnderstanding basic switch statements
🤔
Concept: Learn how traditional switch statements work to select code blocks based on a variable's value.
In C#, a switch statement checks a variable against multiple cases and runs the matching case's code. For example: int day = 3; switch(day) { case 1: Console.WriteLine("Monday"); break; case 2: Console.WriteLine("Tuesday"); break; case 3: Console.WriteLine("Wednesday"); break; default: Console.WriteLine("Unknown day"); break; } This prints "Wednesday" because day is 3.
Result
Output: Wednesday
Understanding switch statements sets the stage for seeing how switch expressions simplify this pattern.
2
FoundationIntroducing switch expressions syntax
🤔
Concept: Learn the new, shorter syntax of switch expressions that return values directly.
Switch expressions use the => arrow and curly braces with cases separated by commas. Example: int day = 3; string name = day switch { 1 => "Monday", 2 => "Tuesday", 3 => "Wednesday", _ => "Unknown day" }; Console.WriteLine(name); Here, the switch expression returns the string for the matching day.
Result
Output: Wednesday
Switch expressions reduce code by returning values directly, avoiding break statements and extra lines.
3
IntermediateUsing pattern matching in switch expressions
🤔Before reading on: do you think switch expressions can match types or conditions, not just exact values? Commit to your answer.
Concept: Switch expressions can match patterns like types, conditions, or properties, not just fixed values.
You can write cases that check for types or conditions: object obj = 42; string result = obj switch { int i when i > 0 => "Positive integer", int i => "Integer", string s => "String", _ => "Other" }; Console.WriteLine(result); This prints "Positive integer" because obj is 42, a positive int.
Result
Output: Positive integer
Pattern matching in switch expressions lets you write flexible, readable conditions without nested ifs.
4
IntermediateCombining multiple patterns in one case
🤔Before reading on: can a single switch expression case handle multiple values or patterns? Guess yes or no.
Concept: You can combine multiple values or patterns in one case using the or (|) operator.
Example: int number = 1; string text = number switch { 1 or 3 or 5 => "Odd small number", 2 or 4 or 6 => "Even small number", _ => "Other" }; Console.WriteLine(text); This prints "Odd small number" because number is 1.
Result
Output: Odd small number
Combining patterns reduces repetition and makes code clearer when multiple cases share the same result.
5
AdvancedUsing switch expressions with complex objects
🤔Before reading on: do you think switch expressions can match properties inside objects? Commit your guess.
Concept: Switch expressions can match object properties using property patterns for detailed decisions.
Example: record Person(string Name, int Age); Person p = new("Alice", 30); string category = p switch { { Age: < 18 } => "Child", { Age: >= 18 and < 65 } => "Adult", { Age: >= 65 } => "Senior", _ => "Unknown" }; Console.WriteLine(category); This prints "Adult" because Alice is 30.
Result
Output: Adult
Matching object properties directly in switch expressions enables clear, expressive code for complex data.
6
ExpertHow switch expressions compile and optimize
🤔Before reading on: do you think switch expressions always compile to simple jump tables like old switches? Guess yes or no.
Concept: Switch expressions compile into efficient code, sometimes using jump tables or decision trees depending on patterns.
The C# compiler analyzes switch expressions and generates optimized IL code. For simple constant matches, it uses jump tables for speed. For complex patterns, it creates nested if-else logic. This means switch expressions are both concise in code and efficient at runtime. Example: The expression int x = 2; string s = x switch { 1 => "One", 2 => "Two", _ => "Other" }; compiles to a jump table, while pattern matches compile to if-else chains.
Result
Switch expressions run efficiently with minimal overhead.
Knowing how switch expressions compile helps write performant code and trust the new syntax in production.
Under the Hood
Switch expressions are expressions that evaluate a value and match it against patterns in order. The compiler generates code that tests each pattern in sequence or uses jump tables for constants. When a pattern matches, the corresponding expression is evaluated and returned immediately. The underscore (_) pattern acts as a catch-all default. Internally, the compiler transforms the switch expression into a series of conditional checks or optimized jump tables depending on the cases.
Why designed this way?
Switch expressions were introduced to make code more concise and expressive, reducing boilerplate and errors common in traditional switch statements. They build on pattern matching introduced earlier in C# to unify decision logic into expressions that return values. This design balances readability, flexibility, and performance, improving developer productivity and code quality.
Input Value
   │
   ▼
┌─────────────────────────────┐
│ Switch Expression Evaluator  │
│ ┌─────────────────────────┐ │
│ │ Pattern 1? ── Yes ──► Return Result 1
│ │    │
│ │    No
│ │    ▼
│ │ Pattern 2? ── Yes ──► Return Result 2
│ │    │
│ │    No
│ │    ▼
│ │   ...
│ │    │
│ │ Pattern N? ── Yes ──► Return Result N
│ │    │
│ │    No
│ │    ▼
│ │ Default (_) ──► Return Default Result
│ └─────────────────────────┘ │
└─────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does a switch expression require all possible cases to be covered explicitly? Commit yes or no.
Common Belief:Switch expressions must list every possible value explicitly or they won't compile.
Tap to reveal reality
Reality:Switch expressions require a default case (_) to cover unmatched values, but you don't need to list every possible value explicitly.
Why it matters:Without a default case, the code won't compile, but adding it lets you handle unexpected inputs safely and keeps code concise.
Quick: Can switch expressions execute multiple cases like traditional switch statements? Guess yes or no.
Common Belief:Switch expressions can run multiple matching cases in sequence like old switch statements.
Tap to reveal reality
Reality:Switch expressions return immediately after the first matching case; they do not fall through or run multiple cases.
Why it matters:Expecting fall-through behavior leads to bugs; switch expressions are designed for clear, single-result decisions.
Quick: Are switch expressions slower than traditional switch statements? Commit your guess.
Common Belief:Switch expressions are slower because they are newer and more complex.
Tap to reveal reality
Reality:Switch expressions compile into efficient code, often as fast or faster than traditional switches due to compiler optimizations.
Why it matters:Misunderstanding performance can prevent developers from using switch expressions, missing out on cleaner code.
Quick: Can switch expressions only match simple values? Guess yes or no.
Common Belief:Switch expressions only work with simple constants like numbers or strings.
Tap to reveal reality
Reality:Switch expressions support complex pattern matching including types, properties, and conditions.
Why it matters:Knowing this unlocks powerful, expressive code patterns beyond simple value matching.
Expert Zone
1
Switch expressions can be nested inside each other to handle multi-level decision trees cleanly.
2
The order of patterns matters: the first matching pattern is chosen, so more specific patterns should come before general ones.
3
Using discard (_) as a default pattern is mandatory to ensure exhaustiveness and avoid runtime exceptions.
When NOT to use
Avoid switch expressions when you need to execute multiple statements per case or require fall-through behavior; traditional switch statements or if-else chains are better. Also, for very complex logic with side effects, clearer imperative code may be preferable.
Production Patterns
In production, switch expressions are used for mapping enums to strings, categorizing data by properties, and simplifying complex conditional logic in APIs and business rules. They often appear in expression-bodied members and LINQ queries for concise transformations.
Connections
Pattern Matching
Switch expressions build on and extend pattern matching capabilities in C#.
Understanding pattern matching deeply helps write more powerful and readable switch expressions.
Functional Programming Expressions
Switch expressions resemble functional programming's expression-based conditionals like 'match' in F# or Scala.
Seeing switch expressions as expressions, not statements, aligns C# with functional programming ideas, improving composability.
Decision Trees in Machine Learning
Switch expressions conceptually mirror decision trees by selecting outcomes based on conditions.
Recognizing this connection helps understand how branching logic can be structured efficiently in code and algorithms.
Common Pitfalls
#1Forgetting the default case (_) in switch expressions.
Wrong approach:int x = 5; string result = x switch { 1 => "One", 2 => "Two" };
Correct approach:int x = 5; string result = x switch { 1 => "One", 2 => "Two", _ => "Other" };
Root cause:Switch expressions require exhaustiveness; missing default causes compile errors.
#2Expecting fall-through behavior in switch expressions.
Wrong approach:int x = 1; switch (x) { case 1: Console.WriteLine("One"); case 2: Console.WriteLine("Two"); break; }
Correct approach:int x = 1; string result = x switch { 1 => "One", 2 => "Two", _ => "Other" }; Console.WriteLine(result);
Root cause:Switch expressions do not support fall-through; they return a single value immediately.
#3Using statements instead of expressions inside switch expressions.
Wrong approach:int x = 2; string result = x switch { 1 => Console.WriteLine("One"), 2 => Console.WriteLine("Two"), _ => Console.WriteLine("Other") };
Correct approach:int x = 2; string result = x switch { 1 => "One", 2 => "Two", _ => "Other" }; Console.WriteLine(result);
Root cause:Switch expressions require expressions that produce values, not statements like Console.WriteLine.
Key Takeaways
Switch expressions in C# provide a concise, readable way to select values based on patterns.
They return values directly and require a default case to handle unmatched inputs.
Pattern matching inside switch expressions allows complex conditions beyond simple values.
Switch expressions compile into efficient code, balancing clarity and performance.
Understanding switch expressions unlocks more expressive and maintainable C# code.