How to resize an array in C#

Share

The Array class in the System namespace provides the Resize() method, which can be used to updateincrease or decrease the size of an existing array in C#.

Syntax

public static void Resize<T> (ref T[]? array, int newSize);

It takes the one-dimensional array to resize and returns its new size as input.

Notes

  • If the new length is equal to the length of the old array, this method does not do anything.
  • If the new length is greater than the existing length of the array, an array of the new length is created, and all the elements of the old array are copied over to the new array.
  • If the user-provided new length is less than the length of the existing array, a new array is created, and elements of the existing array are copied until the new array is filled. The rest of the exiting array elements are ignored.
  • This method only works on one-dimensional arrays.
  • This is an O(n) complexity method, where n is the new length of the array.

In the code below, we have created an array of strings named months to store the names of the first three months of a quarter.

Let’s say we now want to store all twelve months of the year. We will resize the same months array for this, and use the Array.Resize() method to pass 12 as the new Length of the array.

 Array.Resize(ref months, months.Length + 9);

Notice that after the resize operation, the length of the array is 12, and it has space to store another nine strings.

Initial-Months Array - Length : 3
0 : January
1 : Feburary
2 : March

After Resize-Months Array : Length : 12
0 : January
1 : Feburary
2 : March
3 : 
4 : 
5 : 
6 : 
7 : 
8 : 
9 : 
10 : 
11 : 

Code

using System;
public class ArrayResizer
{
public static void Main() {
String[] months = {"January","Feburary", "March"};
Console.WriteLine("Initial-Months Array - Length : {0}",months.Length );
PrintArray(months);
Array.Resize(ref months, months.Length + 9);
Console.WriteLine("After Resize-Months Array : Length : {0}",months.Length);
PrintArray(months);
}
public static void PrintArray(String[] array) {
for(int i = 0; i < array.Length; i++)
{
Console.WriteLine("{0} : {1}", i, array[i]);
}
Console.WriteLine();
}
}