This post will discuss how to add new elements to an array in C#.

Since we can’t modify the array’s size once it is created in C#, there is no direct way to resize the fixed-size arrays to accommodate additional element(s).

If we need a resizable array-based implementation, the recommended solution is to use a List. As elements are added to the List, its capacity grows automatically. But if you insist on using arrays, you have to instantiate a new array to accommodate the additional element. We can do this with any of the following methods:

1. Using Array.CopyTo() method

We can also use the Array.CopyTo() method to allocate the larger array for accommodating the new element. The following code example shows how to resize the array to add a new element.

Download  Run Code

 
The following implementation uses a custom routine in place of the Array.CopyTo() method for copying all the elements of the current array instance to the new array.

Download  Run Code

2. Using Enumerable.Concat() method

We can use Linq’s Concat() method to concatenate elements of the two input sequences. The following code example demonstrates the usage of the Concat() method for appending an element to an array:

Download  Run Code

3. Using Array.Resize() method

The recommended solution to resize a one-dimensional array is by using the Array.Resize() method. This method allocates a new array with the specified size, copies elements from the old array to the new one, and replaces the old array with the new one.

The following example demonstrates the resizing operation with runs in O(n) time, where n is the size of the new array.

Download  Run Code

4. Convert to List

The idea is first to convert the array into a List, then append the specified element at the end of this list, and cast the result back to an array. This is demonstrated below:

Download  Run Code

 
We can do this in a single step by combining the list constructor with the initializer syntax.

Download  Run Code

That’s all about adding new elements to an array in C#.