Common bugs from reference sharing in C Sharp (C#) - Time & Space 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.
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 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.
Each call to Modify goes through all items in the array once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 20 (2 * 10) |
| 100 | 200 (2 * 100) |
| 1000 | 2000 (2 * 1000) |
Pattern observation: The total work doubles because the same array is processed twice.
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.
[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.
Understanding how shared references affect repeated operations helps you reason about performance and bugs in real code.
"What if the Modify method created a new array instead of changing the shared one? How would the time complexity change?"