Passing Arrays to Functions
Arrays can be passed to a function just like any other variable:
// Print all the numbers inside an int array
static void PrintAll(int[] numbers)
{
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
}
}
HOWEVER, unlike int, bool, or double, changes made to an array inside a function also change the original array!
Value vs Array: Side by Side
Given the below program:
static void Main()
{
int numberA = 5;
int[] myArray = { 2, 3 };
ChangeNumbers(numberA, myArray);
Console.WriteLine(numberA); // 5 (unchanged)
Console.WriteLine(myArray[0]); // 44 (changed!)
}
static void ChangeNumbers(int number, int[] list)
{
number = 55;
list[0] = 44;
}
numbergets a copy of the value ofnumberA, so changing it does nothing outside the functionlistgets a copy of the reference tomyArray, so both names point to the same array
To see why, we need to look at how C# stores data.
Value Types vs Reference Types
Every C# data type falls into one of two categories:
| category | examples | the variable holds |
|---|---|---|
| Value type | int, double, bool, char | the value itself |
| Reference type | arrays, objects | an address of where the values are stored |
In the diagram below, the red arrow shows what the variable name points to. For a reference type, that memory holds an address (purple arrow) leading to a second location, where the actual array values live.

What Happens During the Call
Step 1: Calling the function
When ChangeNumbers(numberA, myArray) runs, each parameter becomes a brand new local variable with its own memory address:
numberis created and the value5is copied into itlistis created and the reference stored inmyArrayis copied into it

Step 2: Running the function
number = 55changes only the local copy (numberAis still5)list[0] = 44follows the reference to the shared array, somyArray[0]becomes44too

Modifying vs Replacing
Only changes to the array's elements reach the original. Assigning a whole new array to the parameter does not:
static void Replace(int[] list)
{
list = new int[] { 9, 9 }; // list now points to a NEW array
list[0] = 100; // changes the new array only
}
Here list[0] = ... modifies the shared array. list = ... just points list somewhere else, as demonstrated below:
int[] myArray = { 2, 3 };
Replace(myArray);
Console.WriteLine(myArray[0]); // 2 (unchanged)