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

Type checking patterns in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Type checking patterns
O(n * m)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Explain the growth pattern intuitively.

Input Size (n)Approx. Operations
1 object, 2 type checksUp to 2 checks
1 object, 5 type checksUp to 5 checks
10 objects, 3 type checks eachUp 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.

Final Time Complexity

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.

Common Mistake

[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.

Interview Connect

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.

Self-Check

"What if we replaced the if-else type checks with a switch expression using pattern matching? How would the time complexity change?"