Arrays in C# are special because they are stored as references. This means when you change an array through one variable, other variables pointing to the same array see the change too.
Array as reference type behavior in C Sharp (C#)
using System; class Program { static void Main() { int[] originalArray = {1, 2, 3}; int[] referenceToArray = originalArray; // Both variables point to the same array referenceToArray[0] = 10; // Change affects originalArray too Console.WriteLine(originalArray[0]); // Prints 10 } }
Arrays are reference types in C#, so variables hold references (addresses) to the actual array data.
Assigning one array variable to another copies the reference, not the array contents.
int[] emptyArray = new int[0]; int[] anotherReference = emptyArray; anotherReference = new int[5]; // Now points to a new array, original emptyArray unchanged
int[] singleElementArray = {5}; int[] referenceCopy = singleElementArray; referenceCopy[0] = 20; // singleElementArray[0] is now 20 too
int[] array = {1, 2, 3}; int[] reference = array; reference[2] = 99; // array[2] is now 99
This program shows that changing the array through one variable changes it for the other because both point to the same array.
using System; class Program { static void PrintArray(string label, int[] array) { Console.Write(label + ": "); foreach (int item in array) { Console.Write(item + " "); } Console.WriteLine(); } static void Main() { int[] originalArray = {1, 2, 3}; Console.WriteLine("Before change:"); PrintArray("originalArray", originalArray); int[] referenceToArray = originalArray; // reference copy referenceToArray[1] = 20; // change through reference Console.WriteLine("After change through referenceToArray:"); PrintArray("originalArray", originalArray); PrintArray("referenceToArray", referenceToArray); } }
Time complexity: Access and modification by index is O(1).
Space complexity: No extra space used when copying references.
Common mistake: Expecting that assigning one array variable to another copies the array contents, but it only copies the reference.
Use this behavior when you want multiple parts of your program to work on the same array data without copying.
Arrays in C# are reference types, so variables hold references to the actual array.
Assigning one array variable to another copies the reference, not the array itself.
Changing the array through any reference changes the original array data.