How To Resize An Array In C#?
How To C#

How To Resize An Array In C#?

Mishel Shaji
Mishel Shaji

Resizing an array is usually done if the exact number of elements that have to be stored in an array is unknown. Fortunately, C# has a method called Array.Resize().

Array.Resize() Method

With the Array.Resize() method, we can resize any existing array to a new size. We can expand or shrink the size of an array using this method.

It takes two parameters. The first parameter is the array itself and the second parameter is the new size of the array.

Example

Now, let us resize an array dynamically using the Array.Resize() method.

// Declaring an array with size 2
int[] numbers = { 11, 22 };
Console.WriteLine("Length before resizing: " + numbers.Length);

// Resizing the array to hold 4 elements
Array.Resize(ref numbers, numbers.Length + 2);
numbers[2] = 33;
numbers[3] = 44;

Console.WriteLine("Length after resizing: " + numbers.Length);

We can shrink the size of an existing array. Here's an example.

// Declaring an array with size 4.
int[] numbers = { 11, 22, 33, 44 };
Console.WriteLine("Length before resizing: " + numbers.Length);
Console.WriteLine("Elements are: " + string.Join(", ", numbers));

// Resizing the array to 2.
Array.Resize(ref numbers, 2);
Console.WriteLine("Length after resizing: " + numbers.Length);
Console.WriteLine("Elements are: " + string.Join(", ", numbers));

If you have any questions, please share them in the comments below.