Type patterns in C Sharp (C#) - Time & Space Complexity
When using type patterns in C#, we often check an object's type to decide what to do next.
We want to see how the time it takes grows as we check more objects or more complex types.
Analyze the time complexity of the following code snippet.
object[] items = new object[] { 1, "hello", 3.14, true, new List<int>() };
foreach (var item in items)
{
if (item is int i)
Console.WriteLine($"Integer: {i}");
else if (item is string s)
Console.WriteLine($"String: {s}");
else
Console.WriteLine("Other type");
}
This code checks each item in an array to see if it matches certain types and prints a message accordingly.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each item in the array and checking its type.
- How many times: Once for each item in the array (n times, where n is the number of items).
As the number of items grows, the program checks each one once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 type checks |
| 100 | About 100 type checks |
| 1000 | About 1000 type checks |
Pattern observation: The number of operations grows directly with the number of items.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items checked.
[X] Wrong: "Checking types inside the loop makes it slower in a way that depends on the number of type options."
[OK] Correct: The number of type checks per item is fixed and small, so it does not grow with input size. The main cost grows only with how many items there are.
Understanding how type checks inside loops affect performance helps you write clear and efficient code, a skill valued in many programming tasks.
"What if we added nested loops that check types inside each item? How would the time complexity change?"
Practice
if statement like if (obj is string s)?Solution
Step 1: Understand the
Theiskeyword with type patterniskeyword checks if the object is of the specified type.Step 2: Recognize the pattern variable assignment
If the check is true, the object is assigned to the variablesof that type.Final Answer:
Checks ifobjis a string and assigns it tosif true -> Option CQuick Check:
Type pattern = Check and assign [OK]
- Thinking it converts without checking
- Assuming it always returns true
- Expecting an exception on type mismatch
if statement in C#?Solution
Step 1: Recall correct type pattern syntax
The correct syntax isif (variable is Type name).Step 2: Check each option
if (obj is int number) { } matches the correct syntax. Options B, C, and D have incorrect order or keywords.Final Answer:
if (obj is int number) { } -> Option DQuick Check:
Correct syntax = if (obj is Type name) [OK]
if (obj is Type var) [OK]- Swapping type and variable order
- Using 'as' instead of 'is' for pattern
- Placing keywords incorrectly
object obj = 42;
if (obj is int number)
{
Console.WriteLine(number + 10);
}
else
{
Console.WriteLine("Not an int");
}
Solution
Step 1: Check the type of
objobjholds the integer 42, soobj is intis true.Step 2: Calculate the output inside the
The variableifblocknumberis assigned 42, sonumber + 10equals 52, which is printed.Final Answer:
52 -> Option AQuick Check:
Type check true, output = 42 + 10 = 52 [OK]
- Expecting 'Not an int' output
- Confusing type check with cast
- Thinking code throws error
object obj = "hello";
if (obj is int number)
{
Console.WriteLine(number);
}
Solution
Step 1: Analyze the type check condition
objis a string, soobj is int numberis false.Step 2: Understand the effect on output
Since theifcondition is false and noelseblock exists, nothing is printed.Final Answer:
No output becauseobjis not an int -> Option AQuick Check:
False type check = no output [OK]
- Expecting runtime exception
- Thinking else block is mandatory
- Assuming it prints the string
<pre>string Describe(object input)
{
return input switch
{
int i => $"Integer: {i}",
string s => $"String: {s}",
null => "Null value",
_ => "Unknown type"
};
}
What is the result of
Describe(3.14)?Solution
Step 1: Check the switch cases for input 3.14
3.14 is adouble, which does not matchint,string, ornull.Step 2: Identify the default case
The underscore_matches any other type, so it returns "Unknown type".Final Answer:
"Unknown type" -> Option BQuick Check:
Switch default case = "Unknown type" [OK]
- Assuming 3.14 is int or string
- Expecting compilation error
- Ignoring default case
Ready to prove it?
Pass the test and this pattern moves unknown
