Skip to main content

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;
}
  1. number gets a copy of the value of numberA, so changing it does nothing outside the function
  2. list gets a copy of the reference to myArray, 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:

categoryexamplesthe variable holds
Value typeint, double, bool, charthe value itself
Reference typearrays, objectsan 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.

ref

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:

  1. number is created and the value 5 is copied into it
  2. list is created and the reference stored in myArray is copied into it

ref

Step 2: Running the function​

  1. number = 55 changes only the local copy (numberA is still 5)
  2. list[0] = 44 follows the reference to the shared array, so myArray[0] becomes 44 too

ref

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)