Why pattern matching matters in C Sharp (C#) - Performance Analysis
When using pattern matching in C#, it is important to understand how it affects the speed of your program.
We want to know how the time to check patterns grows as we add more cases or more complex patterns.
Analyze the time complexity of this pattern matching example.
string Describe(object obj) {
return obj switch {
int i => $"Integer {i}",
string s => $"String {s}",
null => "Null value",
_ => "Unknown type"
};
}
This code checks the type of an object and returns a description based on the pattern matched.
Look at what repeats when matching patterns.
- Primary operation: Checking each pattern case one by one.
- How many times: Up to the number of patterns until one matches.
As you add more pattern cases, the program may check more before finding a match.
| Number of Patterns (n) | Approx. Checks |
|---|---|
| 3 | Up to 3 checks |
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
Pattern observation: The number of checks grows linearly with the number of patterns.
Time Complexity: O(n)
This means the time to find a matching pattern grows in direct proportion to how many patterns you have.
[X] Wrong: "Pattern matching always runs in constant time because it looks simple."
[OK] Correct: Each pattern is checked one after another until a match is found, so more patterns mean more checks.
Understanding how pattern matching scales helps you write efficient code and explain your choices clearly in interviews.
What if we used a dictionary lookup instead of switch pattern matching? How would the time complexity change?
Practice
Solution
Step 1: Understand pattern matching purpose
Pattern matching lets you check a variable's type and extract its data in a single, clear step.Step 2: Compare with other options
Options A, B, and D describe unrelated or incorrect benefits not provided by pattern matching.Final Answer:
It simplifies checking types and extracting data in one step. -> Option AQuick Check:
Pattern matching = Simplifies type checks [OK]
- Thinking pattern matching speeds up CPU performance
- Confusing pattern matching with syntax error fixing
- Believing pattern matching replaces loops
is in C#?Solution
Step 1: Recall correct pattern matching syntax
The correct syntax usesis Type variableinside the if condition, likeobj is int number.Step 2: Identify syntax errors in other options
Options A, B, and C have incorrect order or punctuation that cause syntax errors.Final Answer:
if (obj is int number) { /* use number */ } -> Option AQuick Check:
Correct pattern matching syntax = if (obj is int number) { /* use number */ } [OK]
- Placing variable before type in 'is' expression
- Using colon ':' instead of space
- Mixing order of keywords
object obj = 42;
switch (obj)
{
case int i:
Console.WriteLine($"Integer: {i}");
break;
case string s:
Console.WriteLine($"String: {s}");
break;
default:
Console.WriteLine("Unknown type");
break;
}Solution
Step 1: Identify the type of obj
obj is assigned the integer value 42, so its runtime type is int.Step 2: Match switch cases
The switch matchescase int ibecause obj is an int, so it prints "Integer: 42".Final Answer:
Integer: 42 -> Option BQuick Check:
obj is int 42, so output = "Integer: 42" [OK]
- Assuming obj is string because of quotes missing
- Thinking default case runs first
- Confusing compile-time and runtime types
object obj = "hello";
if (obj is int number)
{
Console.WriteLine(number);
}Solution
Step 1: Analyze the type of obj
obj holds a string "hello", but the pattern checks if obj is an int.Step 2: Understand pattern matching behavior
Since obj is a string, the conditionobj is int numberis false, so the block never runs.Final Answer:
The pattern matching condition will never be true for a string. -> Option DQuick Check:
obj is string, pattern checks int, so condition false [OK]
- Assuming variable 'number' must be declared separately
- Thinking 'is' cannot be used with variables
- Ignoring that condition can be false without error
List<object> items = new() { 1, -2, "two", 3.0, null };, which pattern matching expression correctly counts only the positive integer values?Solution
Step 1: Understand the goal
We want to count only positive integers in the list, ignoring other types and null.Step 2: Analyze each option
items.Count(item => item is int) counts all ints but does not filter by value; items.Count(item => item is int number && number > 0) counts ints greater than 0, which matches positive integers; items.Count(item => item is string s) counts strings; items.Count(item => item != null) counts all non-null items.Step 3: Choose the best option
items.Count(item => item is int number && number > 0) uses pattern matching with a condition to count only positive integers, which is a precise use of pattern matching.Final Answer:
items.Count(item => item is int number && number > 0) -> Option CQuick Check:
Pattern matching with condition filters integers correctly [OK]
- Counting all ints without condition when needed
- Counting strings or non-null items by mistake
- Not using variable in pattern matching for conditions
Ready to prove it?
Pass the test and this pattern moves unknown
