Passing an Array by Reference

You can pass an array by reference to a method, using the ref or out parameter modifier, when you want the method to change the parameter to refer to a different array.
Here’s an example of a method that accepts an array and then overwrites the reference so that it points to a new array.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static void DoubleADogList(ref Dog[] list)
{
    Dog[] bigList = new Dog[2 * list.Count()];
 
    int i2 = 0;
    foreach (Dog d in list)
    {
        bigList[i2++] = new Dog(d.Name, d.Age, d.Motto);
        bigList[i2++] = new Dog(d.Name + " Clone", d.Age, d.Motto);
    }
 
    // Change original reference to refer to new list
    list = bigList;
}
We can call this method, passing it an array. When the method returns, the array variable points to the new (larger) array.
1
2
3
4
5
6
Dog d1 = new Dog("Kirby", 13, "Chase balls");
Dog d2 = new Dog("Jack", 17, "Bark");
 
Dog[] list = new Dog[] { d1, d2 };
 
Dog.DoubleADogList(ref list);