Type checking patterns in C Sharp (C#) - Time & Space Complexity
When we use type checking patterns in C#, the program decides what to do based on the type of an object. Understanding how long this decision takes helps us write faster code.
We want to know how the time to check types grows as we have more objects or more complex checks.
Analyze the time complexity of the following code snippet.
object obj = GetObject();
if (obj is int number)
{
Console.WriteLine($"Integer: {number}");
}
else if (obj is string text)
{
Console.WriteLine($"String: {text}");
}
else
{
Console.WriteLine("Unknown type");
}
This code checks the type of obj and runs different code depending on whether it is an integer, a string, or something else.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The program performs a series of type checks on a single object.
- How many times: Each type check runs once in sequence until one matches or all fail.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 1 object, 2 type checks | Up to 2 checks |
| 1 object, 5 type checks | Up to 5 checks |
| 10 objects, 3 type checks each | Up to 30 checks total |
Pattern observation: The number of type checks grows with the number of objects and the number of type checks per object.
Time Complexity: O(n * m)
This means the time grows proportionally with the number of objects n and the number of type checks m done on each object.
[X] Wrong: "Type checking is always instant and does not depend on how many checks we do."
[OK] Correct: Each type check takes time, so more checks or more objects mean more total time spent.
Understanding how type checking scales helps you write clear and efficient code. It shows you can think about how your code behaves as it handles more data, a skill valued in real projects.
"What if we replaced the if-else type checks with a switch expression using pattern matching? How would the time complexity change?"