monstertjie_za monstertjie_za - 1 year ago 32
C# Question

Heap allocation when passing by ref and instantiating new object

Let's say I have the following code:

var person = new Person();
Manipulate(ref person);

And the following method:

public void Manipulate(ref Person pObject)
pObject = new Person();

Does the
method, when instantiating a new Person object, point to the same location on the Heap and create the pObject in that location, or does it create a new location on the heap?

Answer Source

The answer is in the Docs:

The storage location of the object is passed to the method as the value of the reference parameter. If you change the value in the storage location of the parameter (to point to a new object), you also change the storage location to which the caller refers.

To make it clear, check the below example:

static int[] array = new int[] { 5 };

static void Main(string[] args)
    var array2 = array;
    ModifyRef(ref array2);

    foreach (var item in array)
    foreach (var item in array2)

private static void ModifyRef(ref int[] array)
    array = new int[1];
    array[0] = 10;



Making the pointer passed by reference refer to a new object doesn't mean that the old object was replace. array2 now points to a new reference, but array still points to the same old array in memory.