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

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

Choose your learning style9 modes available
Time Complexity: Property patterns
O(n)
Understanding Time Complexity

When using property patterns in C#, we want to know how the time to check these patterns changes as the input grows.

We ask: How does the number of property checks grow when we match more objects or more properties?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


public bool IsPersonAdult(Person p) {
    return p is { Age: >= 18, Name: { Length: > 0 } };
}

// Person class has properties Age (int) and Name (string)

This code checks if a Person object has Age 18 or older and a non-empty Name using property patterns.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Checking each property in the pattern (Age and Name.Length).
  • How many times: Once per call for each property; no loops inside this snippet.
How Execution Grows With Input

Each time we check a Person object, the number of property checks stays the same because the pattern has a fixed number of properties.

Input Size (n)Approx. Operations
1020 (2 checks x 10 objects)
100200 (2 checks x 100 objects)
10002000 (2 checks x 1000 objects)

Pattern observation: The total work grows directly with the number of objects checked, but each object requires a fixed small number of property checks.

Final Time Complexity

Time Complexity: O(n)

This means the time grows linearly with the number of objects we check, since each object requires a fixed number of property checks.

Common Mistake

[X] Wrong: "Checking property patterns is slow because it looks inside many properties and must do a lot of work."

[OK] Correct: The number of properties checked is fixed by the pattern, so each check takes about the same small time, no matter how many objects you test.

Interview Connect

Understanding how property patterns scale helps you explain how your code behaves with more data, showing you think about efficiency and real-world use.

Self-Check

"What if the pattern included a nested collection property that you loop through? How would the time complexity change?"