Reputation: 23789
Suppose I write
int numbers[] = {1,2,3};
ref int second = ref numbers[1];
Array.Resize(ref numbers, 1);
Console.WriteLine(second); // works fine
second = 321; // also legit
How does this work? Have I magically allocated numbers[1]
as a separate, addressable number on the managed heap? What's going on here?
Upvotes: 3
Views: 71
Reputation: 391276
Array.Resize
creates a new array, leaving the old one on the heap, as per the documentation:
This method allocates a new array with the specified size, copies elements from the old array to the new one, and then replaces the old array with the new one.
(my emphasis)
Note: The documentation is slightly misleading depending on how you understand it. It says "then replaces the old array with the new one". What it means is that it replaces the reference you have in the array variable, numbers
in your example, with a reference to the new array. The old array object is left intact and untouched in memory.
If you didn't have a ref int
reference into it, GC would eventually pick it up, but since you do, it doesn't.
second = 321
changes the original array, not the new one.
You can easily show this using a very simple example:
using System;
public class Program
{
public static void Main()
{
int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] b = a;
ref int a1 = ref a[1];
Array.Resize(ref a, 5);
a1 = 100;
Console.WriteLine(a[1]); // new
Console.WriteLine(b[1]); // original
Console.WriteLine(ReferenceEquals(a, b));
}
}
This outputs:
2 // the new array, which did not change
100 // the original array, which did change
false // not the same arrays
So the ref int
variable did change, and the original array did change, but the new, size-modified, copy did not.
See this example on .NET fiddle
Upvotes: 9
Reputation: 1067
This method allocates a new array with the specified size, copies elements from the old array to the new one, and then replaces the old array with the new one.array must be a one-dimensional array.
If array is null, this method creates a new array with the specified size.
If newSize is greater than the Length of the old array, a new array is allocated and all the elements are copied from the old array to the new one. If newSize is less than the Length of the old array, a new array is allocated and elements are copied from the old array to the new one until the new one is filled; the rest of the elements in the old array are ignored. If newSize is equal to the Length of the old array, this method does nothing.
Straight from MSDN
Upvotes: 3