Question about Array.Resize method - Why using reference

Hello fellow C# and .NET enthusiasts. While working through Part 4 (Arrays) of the Microsoft Foundation C# course, I stumbled over an issue I had with the array.Resize method. I was constantly trying this:

Array.Resize (var pallets, 6;

Of course I got the red squiggly lines. I then learned to use this:

Array.Resize (ref pallets, 6);

Microsoft did not explain this in detail, but they mentioned that it has to do with the way .NET manages objects and storage. Now here is a question to check my understanding about why I need to use ref here instead of var. Would be thankful, if someone could tell me if I’m right or wrong with this. Thanks in advance.

By using the Array.Resize method, I am changing the structure of the Array and therefore .NET has to ask for new memory in the heap. When I use for example Array.Clear, then this does not happen, because I only change values, that are already assigned to the array, but still residing in the heap?

Right? Please say yes! :rofl:

Once an array is created, it cannot be resized. Array.Resize() actually does a trick- It doesn’t resize the original array. Instead, it creates a new array and changes the reference of the original array to point to the new array.
To learn more about the ref keyword, you can check Passing parameters

OK, I see. Thank you for the link. I will read this later. Have a good time.