Type checking patterns in C Sharp (C#) - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
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?"
Practice
if (obj is string s) do?Solution
Step 1: Understand the
Theispatterniskeyword checks if an object is of a certain type.Step 2: Assign variable if type matches
Ifobjis a string, it assigns the value tosfor use inside the block.Final Answer:
Checks if obj is a string and assigns it to s if true -> Option CQuick Check:
is Type varchecks type and assigns [OK]
is Type var checks and assigns together [OK]- Thinking it converts without checking
- Assuming it checks for null only
- Believing it throws exceptions automatically
obj is an int and assign it to number?Solution
Step 1: Identify correct C# type pattern syntax
The correct syntax usesis Type variableto check and assign.Step 2: Compare options
if (obj is int number) { } usesis int number, which is valid. Others use invalid keywords or syntax.Final Answer:
if (obj is int number) { } -> Option AQuick Check:
is Type varsyntax is correct [OK]
is Type var for type check and assignment [OK]- Using 'as' instead of 'is' for type checking
- Using '==' to compare types
- Using JavaScript or Java keywords like 'instanceof'
object obj = 42;
if (obj is int n)
{
Console.WriteLine(n + 10);
}
else
{
Console.WriteLine("Not an int");
}Solution
Step 1: Check the type of obj
obj holds the integer 42, soobj is int nis true and assigns 42 to n.Step 2: Calculate the output inside the if block
It printsn + 10which is 42 + 10 = 52.Final Answer:
52 -> Option BQuick Check:
Type check passes, output is 42 + 10 = 52 [OK]
- Printing the original obj instead of n + 10
- Choosing else output wrongly
- Thinking it causes a compile error
object obj = "hello";
if (obj is int number)
{
Console.WriteLine(number);
}Solution
Step 1: Analyze the type check
obj is a string, soobj is int numberis false and number is not assigned.Step 2: Understand the effect on code execution
The if block is skipped, so nothing prints. No error or exception occurs.Final Answer:
The variable 'number' is not assigned because obj is not int -> Option DQuick Check:
Type check false means variable not assigned [OK]
- Thinking it causes syntax error
- Expecting runtime exception
- Assuming variable is assigned anyway
List<object> items = new() { 1, "two", 3, null, 4.5 };, which code snippet correctly sums only the integer values using type checking patterns?Solution
Step 1: Understand the list contents
The list has integers, a string, null, and a double. We want to sum only integers.Step 2: Check each option for correct type filtering
int sum = 0; foreach (var item in items) { if (item is int n) sum += n; } Console.WriteLine(sum); usesif (item is int n)to add only integers. int sum = 0; foreach (int n in items) { sum += n; } Console.WriteLine(sum); tries to cast all items to int in foreach, causing error. int sum = 0; foreach (var item in items) { if (item is double d) sum += (int)d; } Console.WriteLine(sum); sums doubles cast to int, which is incorrect. int sum = 0; foreach (var item in items) { sum += (int)item; } Console.WriteLine(sum); casts all items to int without checking, causing runtime errors.Final Answer:
int sum = 0; foreach (var item in items) { if (item is int n) sum += n; } Console.WriteLine(sum); -> Option AQuick Check:
Useis int varto filter integers safely [OK]
if (item is int n) to sum integers safely [OK]- Casting without checking causing exceptions
- Summing wrong types like double or string
- Assuming foreach int works on object list
