SoFunction
Updated on 2025-03-06

Introduction to several ways to expand array capacity in C#

Suppose there is an array of specified length, how to expand the capacity? The easiest thing to think of is to expand the capacity by the following methods:

    class Program
    {
        static void Main(string[] args)
        {
            int[] arrs = new[] {1, 2, 3, 4, 5};
            arrs[5] = 6;
        }
    }

Error: IndexOutOfRanageException is not processed, the index exceeds the array boundary.

Create a temporary array with expanded capacity, then assign the value to the original array, using a loop traversal method

        static void Main(string[] args)
        {
            int[] arrs = new[] {1, 2, 3, 4, 5};
            int[] temp = new int[ + 1];
            //Transfer the arrrs array and assign all elements of the array to the temp array            for (int i = 0; i < ; i++)
            {
                temp[i] = arrs[i];
            }
            // Assign the temporary array to the original array, and the original array has been expanded at this time            arrs = temp;
            // Assign the last position of the original array after expansion            arrs[ - 1] = 6;
            foreach (var item in arrs)
            {
                (item);
            }
            ();
        }

Create a temporary array with an expanded capacity, then assign the value to the original array, using Array's static method

For ordinary copying between arrays like this, the Array class must have prepared static methods for us: ().

        static void Main(string[] args)
        {
            int[] arrs = new[] {1, 2, 3, 4, 5};
            int[] temp = new int[ + 1];
            (arrs, temp, );
            // Assign the temporary array to the original array, and the original array has been expanded at this time            arrs = temp;
            // Assign the last position of the original array after expansion            arrs[ - 1] = 6;
            foreach (var item in arrs)
            {
                (item);
            }
            ();
        }

Use Array's static method to expand capacity

However, copying seems more cumbersome, and we can also use the() method to expand the array.

        static void Main(string[] args)
        {
            int[] arrs = new[] {1, 2, 3, 4, 5};
            (ref arrs,  + 1);
            // Assign the last position of the original array after expansion            arrs[ - 1] = 6;
            foreach (var item in arrs)
            {
                (item);
            }
            ();
        }

Summary: Array expansion is preferred to use Array's static method Resize, and secondly consider assigning an expanded, temporary array to the original array.

The above is the entire content of this article. I hope that the content of this article has certain reference value for your study or work. Thank you for your support. If you want to know more about it, please see the following links