C# Array - Resize() Method



The C# Array Resize() The method manipulates the size of an array by changing the number of elements to a specified new size.

If the new size is less than zero "ArgumentOutOfRangeException" will be thrown.

Syntax

Following is the syntax of the C# Array Resize() method −

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

Parameters

This method accepts the following parameters −

  • Array: The one dimensional zero based array to resize, or null to create new array with the specified size.
  • newSize: The size of the new array.

Return value

This method does not return any value.

Example 1: Resize the Integer Array

Let us crate a basic example of the resize() method to increase the size of the previous integer array by 2 −

    
using System;
class Program
{
   static void Main()
   {
      int[] numbers = { 1, 2, 3, 4, 5 };
      // resize the array
      Array.Resize(ref numbers, numbers.Length + 2);
      Console.WriteLine(string.Join(", ", numbers));
   }
}

Output

Following is the output −

1, 2, 3, 4, 5, 0, 0

Example 2: Resizing to a Smaller Size

Let us see another example of the Resize() method to resizing the integer array to a smaller size −

using System;
class Program
{
   static void Main()
   {
      int[] numbers = { 1, 2, 3, 4, 5 };
      // resize the array
      Array.Resize(ref numbers, 4);
      Console.WriteLine(string.Join(", ", numbers));
   }
}

Output

Following is the output −

1, 2, 3, 4

Example 3: Resizing a String Array

This is another, example of the Resize() method. Here, we use this method to resize a string array −

using System;
class Program
{
   static void Main()
   {
      string[] words = { "apple", "banana", "cherry", "date", "elderberry" };
      Array.Resize(ref words, words.Length + 2);
      Console.WriteLine(string.Join(", ", words));
   }
}

Output

Following is the output −

apple, banana, cherry, date, elderberry, , 

Example 4: Resize String array to Smaller Size

Here, in this example we uses the Resize() method to decrease the size of the string array −

using System;
class Program
{
   static void Main()
   {
      string[] words = { "apple", "banana", "cherry", "date", "elderberry" };
      Array.Resize(ref words, 3);
      Console.WriteLine(string.Join(", ", words));
   }
}

Output

Following is the output −

apple, banana, cherry
csharp_array_class.htm
Advertisements