Pattern matching in switch in C Sharp (C#) - Time & Space Complexity
We want to understand how the time it takes to run a switch statement with pattern matching changes as the input changes.
Specifically, how does the number of checks grow when we add more patterns?
Analyze the time complexity of the following code snippet.
object obj = GetInput();
switch (obj)
{
case int i:
Console.WriteLine($"Integer: {i}");
break;
case string s when s.Length > 5:
Console.WriteLine($"Long string: {s}");
break;
case null:
Console.WriteLine("Null value");
break;
default:
Console.WriteLine("Other type");
break;
}
This code checks the input against several patterns to decide what to print.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The switch statement checks each pattern one by one until it finds a match.
- How many times: At most, it checks all patterns once each in order.
Each new pattern adds one more check to do in the worst case.
| Input Size (number of patterns) | Approx. Operations (pattern checks) |
|---|---|
| 4 | Up to 4 checks |
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
Pattern observation: The number of checks grows directly with the number of patterns.
Time Complexity: O(n)
This means the time to find a matching pattern grows linearly with the number of patterns to check.
[X] Wrong: "The switch with pattern matching checks all patterns instantly or in constant time."
[OK] Correct: The switch checks patterns one after another until it finds a match, so more patterns mean more checks.
Understanding how pattern matching scales helps you explain code efficiency clearly and shows you know how language features work under the hood.
What if the switch used a hash-based lookup for patterns? How would the time complexity change?
Practice
switch statement primarily help you do in C#?Solution
Step 1: Understand pattern matching purpose
Pattern matching inswitchlets you test an object's type and properties clearly.Step 2: Compare with other options
Looping, variable declaration, and exception handling are unrelated to pattern matching inswitch.Final Answer:
Check an object's type and properties in a clear way -> Option AQuick Check:
Pattern matching = type and property checks [OK]
- Confusing pattern matching with loops
- Thinking it handles exceptions
- Believing it declares variables automatically
num equal to 10 using pattern matching in a switch expression?Solution
Step 1: Recall correct pattern matching syntax
To match a value with a condition, usecase Type variable when condition:.Step 2: Check each option
case int n when n == 10: useswhen n == 10, which is correct. Others use invalid syntax.Final Answer:
case int n when n == 10: -> Option AQuick Check:
Use 'when' for conditions in pattern matching [OK]
- Using '==' directly after case without 'when'
- Using '=>' or 'is' incorrectly in case
- Omitting the variable name
object obj = 42;
switch (obj)
{
case int n when n > 40:
Console.WriteLine("Greater than 40");
break;
case int n:
Console.WriteLine("Integer");
break;
default:
Console.WriteLine("Other");
break;
}Solution
Step 1: Identify the object type and value
obj is an integer with value 42.Step 2: Evaluate switch cases in order
First case matches int n when n > 40, which is true for 42, so prints "Greater than 40" and breaks.Final Answer:
Greater than 40 -> Option CQuick Check:
Pattern with 'when' matched first [OK]
- Ignoring the 'when' condition
- Assuming second case runs first
- Thinking default runs for int
object val = "hello";
switch (val)
{
case string s when s.Length > 3
Console.WriteLine("Long string");
break;
default:
Console.WriteLine("Other");
break;
}Solution
Step 1: Check switch case syntax
Each case pattern must end with a colon ':' before the statements.Step 2: Locate missing colon
The case line lacks ':' afterwhen s.Length > 3, causing syntax error.Final Answer:
Missing colon ':' after case pattern -> Option BQuick Check:
Case patterns need ':' after condition [OK]
- Forgetting ':' after case pattern
- Adding parentheses around 'when' condition
- Thinking 'when' can't be used with strings
items containing integers and strings, how would you use pattern matching in a switch expression to return a new list of strings where:- Integers greater than 10 become "Big number"
- Strings longer than 5 characters become "Long text"
- All others become "Other"?
Which code snippet correctly implements this?
Solution
Step 1: Understand switch expression syntax
Switch expressions use '=>' for cases, and 'when' for conditions.Step 2: Check each option's syntax
items.Select(item => item switch { int n when n > 10 => "Big number", string s when s.Length > 5 => "Long text", _ => "Other" }).ToList(); uses correct 'item switch { case => result }' with 'when' and '=>'. Other options use invalid syntax ('switch' inside lambda or 'if' instead of 'when'). items.Select(item => item switch { int n when n > 10: "Big number", string s when s.Length > 5: "Long text", _ => "Other" }).ToList(); uses ':' instead of '=>', which is invalid in switch expressions.Final Answer:
items.Select(item => item switch { int n when n > 10 => "Big number", string s when s.Length > 5 => "Long text", _ => "Other" }).ToList(); -> Option DQuick Check:
Switch expressions use '=>' and 'when' [OK]
- Using ':' instead of '=>' in switch expressions
- Using 'if' instead of 'when' for conditions
- Trying to put 'switch' keyword inside lambda
Ready to prove it?
Pass the test and this pattern moves unknown
