Bird
Raised Fist0
C Sharp (C#)programming~10 mins

Switch expressions with patterns in C Sharp (C#) - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Switch expressions with patterns
Start with input value
↓
Evaluate switch expression
↓
Match pattern 1?
No→Match pattern 2?
↓
Return result 1
↓
End
The switch expression checks the input against patterns in order and returns the matching result or a default.
Execution Sample
C Sharp (C#)
object input = 42;
string result = input switch
{
    int i when i > 0 => "Positive integer",
    int i when i < 0 => "Negative integer",
    string s => $"String: {s}",
    _ => "Unknown"
};
This code uses a switch expression to check the input's type and value, returning a matching string.
Execution Table
StepInput ValuePattern CheckedCondition ResultBranch TakenOutput
142int i when i > 0TrueYes"Positive integer"
242int i when i < 0SkippedNo
342string sSkippedNo
442_ (default)SkippedNo
Exit42N/AMatched at step 1End"Positive integer"
💡 Input 42 matches pattern 'int i when i > 0' at step 1, so switch returns "Positive integer" and stops.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
input4242424242
resultnull"Positive integer""Positive integer""Positive integer""Positive integer"
Key Moments - 3 Insights
Why does the switch expression stop checking after the first pattern matches?
Because switch expressions return the result immediately when a pattern matches, as shown in execution_table step 1 where the first pattern matches and the rest are skipped.
What does the underscore (_) pattern mean in the switch expression?
The underscore (_) is the default pattern that matches anything not matched before, as seen in execution_table step 4, but it is skipped here because an earlier pattern matched.
How does the 'when' clause affect pattern matching?
The 'when' clause adds an extra condition to the pattern; the pattern only matches if the condition is true, like 'int i when i > 0' in step 1.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output after step 1?
A"Unknown"
B"Positive integer"
C"Negative integer"
D"String: 42"
💡 Hint
Check the Output column at step 1 in the execution_table.
At which step does the switch expression stop checking patterns?
AStep 3
BStep 4
CStep 1
DStep 2
💡 Hint
Look at the Branch Taken column and see where the first 'Yes' appears.
If input was "hello" (a string), which pattern would match?
Astring s
Bint i when i < 0
Cint i when i > 0
D_ (default)
💡 Hint
Refer to the patterns and their types in the execution_sample code.
Concept Snapshot
Switch expressions check an input against patterns in order.
Each pattern can have a condition with 'when'.
The first matching pattern returns its result immediately.
Use '_' as a default catch-all pattern.
Syntax: result = input switch { pattern1 => value1, pattern2 => value2, _ => defaultValue };
Full Transcript
This example shows how a switch expression in C# tests an input value against several patterns. The input 42 is checked first against 'int i when i > 0', which matches because 42 is a positive integer. The switch returns "Positive integer" immediately and stops checking other patterns. The underscore (_) pattern is a default that matches anything else but is skipped here because an earlier pattern matched. The 'when' clause adds extra conditions to patterns. This flow helps write clear, concise code for multiple conditions.

Practice

(1/5)
1. What does a switch expression with patterns in C# primarily help you do?
easy
A. Create loops that run a fixed number of times
B. Declare variables with dynamic types
C. Match values and types cleanly without long if-else chains
D. Handle exceptions in asynchronous code

Solution

  1. Step 1: Understand switch expressions

    Switch expressions allow matching on values or types in a concise way.
  2. Step 2: Compare with if-else chains

    They replace long if-else chains with clearer, more readable code.
  3. Final Answer:

    Match values and types cleanly without long if-else chains -> Option C
  4. Quick Check:

    Switch expressions = clean matching [OK]
Hint: Switch expressions simplify matching values and types [OK]
Common Mistakes:
  • Confusing switch expressions with loops
  • Thinking switch expressions handle exceptions
  • Believing switch expressions declare variables
2. Which of the following is the correct syntax for a switch expression with a type pattern in C#?
easy
A. var result = obj switch { int i => i * 2, string s => s.Length, _ => 0 };
B. var result = switch obj { int i => i * 2, string s => s.Length, _ => 0 };
C. var result = obj { int i => i * 2, string s => s.Length, _ => 0 } switch;
D. var result = obj switch (int i => i * 2, string s => s.Length, _ => 0);

Solution

  1. Step 1: Identify correct switch expression syntax

    The switch expression syntax is: variable switch { pattern => result, ... }.
  2. Step 2: Match options to syntax

    var result = obj switch { int i => i * 2, string s => s.Length, _ => 0 }; matches this syntax exactly with type patterns and a discard pattern.
  3. Final Answer:

    var result = obj switch { int i => i * 2, string s => s.Length, _ => 0 }; -> Option A
  4. Quick Check:

    Correct switch expression syntax = var result = obj switch { int i => i * 2, string s => s.Length, _ => 0 }; [OK]
Hint: Remember: variable switch { patterns } is correct syntax [OK]
Common Mistakes:
  • Placing switch before the variable
  • Using parentheses instead of braces
  • Misplacing the switch keyword
3. What is the output of the following C# code?
object value = 5;
string result = value switch
{
  int i when i > 0 => "Positive integer",
  int i when i < 0 => "Negative integer",
  string s => "String",
  _ => "Unknown"
};
Console.WriteLine(result);
medium
A. Negative integer
B. Positive integer
C. String
D. Unknown

Solution

  1. Step 1: Analyze the switch expression input

    The variable 'value' is an object holding the integer 5.
  2. Step 2: Match patterns in order

    First pattern matches int i when i > 0, which is true for 5, so result is "Positive integer".
  3. Final Answer:

    Positive integer -> Option B
  4. Quick Check:

    5 > 0 matches first pattern [OK]
Hint: Check pattern order and conditions carefully [OK]
Common Mistakes:
  • Ignoring the 'when' condition
  • Assuming string pattern matches first
  • Choosing default case incorrectly
4. Identify the error in this switch expression code snippet:
object obj = "hello";
var output = obj switch
{
  int i => i.ToString(),
  string s => s.ToUpper(),
  default => "none"
};
medium
A. Patterns must be in parentheses
B. Missing semicolon after switch expression
C. Cannot switch on object type
D. Using 'default' instead of '_' for discard pattern

Solution

  1. Step 1: Check switch expression patterns

    In C# switch expressions, the discard pattern uses '_' not 'default'.
  2. Step 2: Identify the incorrect pattern usage

    The code uses 'default' which causes a syntax error; it should be '_'.
  3. Final Answer:

    Using 'default' instead of '_' for discard pattern -> Option D
  4. Quick Check:

    Discard pattern = '_' not 'default' [OK]
Hint: Use '_' for default case in switch expressions [OK]
Common Mistakes:
  • Using 'default' keyword in switch expressions
  • Confusing switch statements with switch expressions
  • Forgetting to end statements with semicolon
5. Given a list of objects, write a switch expression that returns:
- "Number" if the object is an int or double
- "Text" if the object is a non-empty string
- "Empty" if the object is an empty string
- "Other" for anything else

Which of the following switch expressions correctly implements this logic?
hard
A. obj switch { int _ or double _ => "Number", string s when s.Length == 0 => "Empty", string s when s.Length > 0 => "Text", _ => "Other" }
B. obj switch { int or double => "Number", string s when s == "" => "Empty", string s when s != "" => "Text", _ => "Other" }
C. obj switch { int or double => "Number", string s when s.Length > 0 => "Text", string s when s.Length == 0 => "Empty", _ => "Other" }
D. obj switch { int or double => "Number", string s when s != "" => "Text", string s when s == "" => "Empty", _ => "Other" }

Solution

  1. Step 1: Understand type patterns and conditions

    We must match int or double first, then string with length checks for empty/non-empty.
  2. Step 2: Check order and conditions

    obj switch { int _ or double _ => "Number", string s when s.Length == 0 => "Empty", string s when s.Length > 0 => "Text", _ => "Other" } correctly checks int or double, then string with Length == 0 for "Empty", then Length > 0 for "Text", then default.
  3. Final Answer:

    obj switch { int _ or double _ => "Number", string s when s.Length == 0 => "Empty", string s when s.Length > 0 => "Text", _ => "Other" } -> Option A
  4. Quick Check:

    Order and conditions matter in switch patterns [OK]
Hint: Order patterns from specific to general, check string length for empty [OK]
Common Mistakes:
  • Using 'or' incorrectly without parentheses
  • Checking string emptiness with == "" instead of Length
  • Placing empty string check after non-empty
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard