How To Resize An Array In C#

Introduction 

 This article will discuss how to resize an Array In C#. The Array class in the System namespace provides the Resize() method that can be used to update the size of an existing array in C#. 

Syntax 

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

Essential Points to resize Arrays in C#

  • This method does nothing if the new length is equal to the length of the old array.
  • If the new length is greater than the array's current length, an array of the new length is created, and all of the elements of the old array are copied over to the new array.
  • If the new length specified by the user is less than the length of the existing array, a new array is created, and elements from the existing array are copied until the new array is filled. The remaining array elements are ignored.
  • This method is only applicable to one-dimensional arrays.
  • This method has an O(n) complexity, where n is the array's new length. 

In the code below, we have created an array of strings named flat array to store the names of the first four flats as strings. 

 Array.Resize(ref Flats, Flats.Length + 2);

Let’s say we now want to store two resize Flats.

We will resize the same array size for this and use the Array.Resize() method and add 2 to the length of the array. That means, the new array size will be 6. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ArrayDemo01
{
   internal class DemoArrayClass
    {
        public static void Main()
        {
         
            String[] Flats = {
            "OneBhk",
            "TwoBhk",
            "ThreeBhk",
            "FourBhk"
        };
                Console.WriteLine("Initial-Flats Array - Length : {0}", Flats.Length);
                PrintArray(Flats);
                Array.Resize(ref Flats, Flats.Length + 2);
                Console.WriteLine("After Resize-Flats Array : Length : {0}", Flats.Length);
                PrintArray(Flats);
            }
            public static void PrintArray(String[] array)
            {
                for (int i = 0; i < array.Length; i++)
                {
                    Console.WriteLine("{0} : {1}", i, array[i]);
                }
                Console.WriteLine();
            }
        }

    }

A new array is allocated, and all the elements from the old array are copied to it if newSize is +2 of the length of the old array. 

The output of the above code looks like this. As you an see, the size of the array is 6. 

Output

Conclusion

This code example taught us how to resize an array in C#.

To learn everything about arrays in C#, check out Become a Master of Working With C# Arrays - A Comprehensive Guide to Arrays (c-sharpcorner.com) 


Similar Articles