Array as reference type behavior in C Sharp (C#) - Time & Space Complexity
When we work with arrays in C#, it's important to know how operations on them behave over time.
We want to see how the time to run code changes when arrays are passed or modified.
Analyze the time complexity of the following code snippet.
int[] numbers = {1, 2, 3, 4, 5};
int[] copy = numbers; // copy points to the same array
copy[0] = 10; // changes original array
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
}
This code shows that arrays are reference types, so copying the variable does not copy the data.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that prints each element of the array.
- How many times: It runs once for each element in the array (n times).
The loop runs once for every item in the array, so if the array gets bigger, the work grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print operations |
| 100 | 100 print operations |
| 1000 | 1000 print operations |
Pattern observation: The time grows directly with the number of elements.
Time Complexity: O(n)
This means the time to run the loop grows in a straight line with the array size.
[X] Wrong: "Copying an array variable duplicates all its elements immediately."
[OK] Correct: In C#, the variable holds a reference, so copying it just points to the same array, not a new one.
Understanding how arrays behave as references helps you explain how data changes and performance relate in real code.
"What if we created a new array and copied elements one by one? How would the time complexity change?"