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

Common bugs from reference sharing in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Common bugs from reference sharing
O(n)
Understanding Time Complexity

When objects are shared by reference in C#, some operations repeat depending on how many references exist.

We want to see how the cost grows when multiple parts of code share the same object.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Box {
  public int[] Items;
}

void Modify(Box box) {
  for (int i = 0; i < box.Items.Length; i++) {
    box.Items[i] += 1;
  }
}

Box sharedBox = new Box { Items = new int[1000] };
Modify(sharedBox);
Modify(sharedBox);
    

This code modifies the same array inside a shared object twice by reference.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through the array inside the shared object.
  • How many times: Twice, because the Modify method is called two times on the same object.
How Execution Grows With Input

Each call to Modify goes through all items in the array once.

Input Size (n)Approx. Operations
1020 (2 * 10)
100200 (2 * 100)
10002000 (2 * 1000)

Pattern observation: The total work doubles because the same array is processed twice.

Final Time Complexity

Time Complexity: O(n)

This means the time grows directly with the size of the array, even if the object is shared and modified multiple times.

Common Mistake

[X] Wrong: "Since the object is shared, modifying it multiple times only costs once."

[OK] Correct: Each modification loops through the entire array again, so the cost adds up with each call.

Interview Connect

Understanding how shared references affect repeated operations helps you reason about performance and bugs in real code.

Self-Check

"What if the Modify method created a new array instead of changing the shared one? How would the time complexity change?"