Array.Resize
This .NET method allocates a new array. It then copies existing element values to the new array. This logic is needed when an array's size is inadequate.
We show how Resize reallocates and copies elements. The arguments to Array.Resize
are easy to understand (unless you are unfamiliar with the method).
We use Array.Resize
to replace a large array with a smaller one. This is useful if we have a large array of data, and want to only keep the first part.
Array.Resize
with argument of 2. This call changes an array of 4 elements to one with 2 elements.Array.Resize
can expand, or shrink an array's size.using System; // Step 1: initialize array for example. int[] array = new int[4]; array[0] = 10; array[1] = 20; array[2] = 30; array[3] = 40; for (int i = 0; i < array.Length; i++) { Console.WriteLine("BEFORE: {0}", array[i]); } // Step 2: resize the array from 4 to 2 elements. Array.Resize(ref array, 2); for (int i = 0; i < array.Length; i++) { Console.WriteLine("AFTER: {0}", array[i]); }BEFORE: 10 BEFORE: 20 BEFORE: 30 BEFORE: 40 AFTER: 10 AFTER: 20
Next we expand an array's size. This can be useful for certain data structures, such as those that must accommodate more data but have minimal memory footprint.
Array.Resize
call, we will get an IndexOutOfRangeException
. This exception should be avoided.using System; // Initialize an array with 5 elements. char[] array = new char[5]; array[0] = 'p'; array[1] = 'y'; array[2] = 't'; array[3] = 'h'; array[4] = 'o'; // We need an array with 6 elements. // ... Use Array.Resize to make a new array. Array.Resize<char>(ref array, 6); // Assign the last element. array[5] = 'n'; // Display the array. Console.WriteLine(new string(array));python
A call to Array.Resize
runs through an algorithm that determines that the array needs to be larger or smaller. It copies the array, and then changes the reference.
Array.Resize
does not resize the array. It replaces the array with a new one of a different size.Copying an array completely when resizing it is wasteful in many situations. For these cases, use List
—call Add()
to add to empty space on the end.
Array.Resize
can lead to better performance. Arrays boost memory efficiency and lookup speed.Array.Resize
does not change existing arrays. It allocates and copies elements into a new array. It is useful only when arrays are required.