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

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

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

Scenario Under Consideration

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

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

As the number of items grows, the program checks each one once.

Input Size (n)Approx. Operations
10About 10 type checks
100About 100 type checks
1000About 1000 type checks

Pattern observation: The number of operations grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of items checked.

Common Mistake

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

Interview Connect

Understanding how type checks inside loops affect performance helps you write clear and efficient code, a skill valued in many programming tasks.

Self-Check

"What if we added nested loops that check types inside each item? How would the time complexity change?"