In this article, we are going to learn about the different ways we can add values to a C# array.

To download the source code for the video, visit our Patreon page (YouTube Patron tier).

Let’s dive in.


VIDEO: Different Ways to Populate Arrays in C#.

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!
Become a patron at Patreon!


How to Add Values to a C# Array

Arrays in C# can have a fixed size. We also know that we can assign values to an array at the time of initialization.

After we initialize an array, we might want to add value to the specific index, change the array size to add more values or copy the values from one array into another.

Let’s have a look at the different approaches to adding values to an array. After that, we’ll wrap things up with a performance benchmark to find which approach is the most efficient.

Add Values to C# Array Using the Index Initializer

Using this approach, we can set the value using the specified index or position of an array.

Let’s create a simple integer array of size 3:

var array = new int[3];

In this array, we have 3 indexes namely 0, 1, and 2.

In order to set the value at these indexes, we can use the index initializer:

array[0] = 100;
array[1] = 101;
array[2] = 102;

As we can see, each statement uses an array index to set its value.

However, it is also important to note that if we use any invalid index, then we are thrown the IndexOutOfRangeException. Hence, we need to ensure that the index is always within the range (arraySize - 1).

Use the Array.SetValue() Method to Add Values to C# Array

The next approach is to use the SetValue() method available in Array class:

array.SetValue(value: 100, index: 0);
array.SetValue(value: 101, index: 1);
array.SetValue(value: 102, index: 2);

We can directly invoke the SetValue() method on an array itself. Please note that we need to provide the value as the first parameter and the index as the second parameter. Apart from this, there are multiple overloads available for different use cases.

Again, this method also throws IndexOutOfRangeException for incorrect array index.

Add Values to C# Array Using Populated Collections

There are situations where we have already prepared collections, and we need to use all the elements from those collections to populate our array. 

Let’s see how we can do that.

Array.CopyTo() Method

The first approach to adding values to an array is by using the Array.CopyTo() method. 

Using this method, we can copy all the elements from one array to another array starting at the specified target array index.

To demonstrate this, let’s declare our first array with size 3:

var array1 = new int[3];

After that, let’s create our second array with some elements:

var array2 = new int[] { 100, 101, 102 };

Now, in order to copy all the elements from array2 to array1, we can invoke the CopyTo() method directly on the source array:

array2.CopyTo(array1, 0);

Here, the first parameter is the target array and the second parameter is the starting index of the target array. This method overwrites the elements on the target array. Another important factor is that the target array should have enough size to hold the copied elements.

There’s also another method Array.Copy() that is similar to Array.CopyTo(). The difference is that it copies a range of elements from the source to the target.

Add Values to a C# Array by Using Lists with ToArray method

Another approach that we can use is the  List<T> class. We can add elements to the list and then convert it to an array. 

Let’s define a simple list of integers using the List<T> class:

var list = new List<int>();

Once we have the list object in place, we can add elements to it using the Add() method:

list.Add(100);
list.Add(101);
list.Add(102);

Finally, we can convert the list to an array using ToArray() method:

var array = list.ToArray();

This method works well for scenarios we don’t know the size of the array upfront.

LINQ Concat() Method With the Help of the ToArray Method

Next on, there is the Concat() method in LINQ. This method concatenates two sequences into a single sequence. 

Let’s say we have an array and we need to concatenate all the values from another array, then we can use this method.

To give an example, let’s create our first array with an empty size:

var array1 = Array.Empty<int>();

Our second array contains some values:

var array2 = new int[] { 100, 101, 102 };

Now, let’s concatenate the two arrays into a single one:

array1 = array1.Concat(array2).ToArray();

Here, we’ve used the Concat() method to concatenate two arrays and then we invoked the ToArray() method to convert it back to an array.

Performance Benchmark

Now, let’s dive into the interesting part which is performance comparison. We’ll use the BenchmarkDotNet library to do the benchmark for us.

In this benchmark, we’ll use arrays of different sizes and then compare which approach performs the best in adding values to the array.

Let’s look at one of the approaches that we use for benchmarking:

public static int[] ArrayIndexInitializer(int arraySize)
{
    var array = new int[arraySize];
    for (var index = 0; index < arraySize; index++)
    {
        array[index] = index;
    }

    return array;
}

We assign the values to an array in a loop of varying sizes. The other approaches work similarly and you can check the source code if you’re interested.

It is important to mention that for the first two approaches, we have to populate the array manually using loops. But for other approaches that use already populated collections, we don’t have to do that. We simply use different methods to transfer elements from one collection to the array. Having this in mind, we will group our benchmark results.

Benchmark With 1,000 Elements:

Now, let’s run the benchmark with an array size of 1,000 elements and wait for the result:

|                Method |           Categories | arraySize |       Mean |    Error | Allocated |
|---------------------- |--------------------- |---------- |-----------:|---------:|----------:|
| ArrayIndexInitializer |               Manual |      1000 |   304.2 ns |  1.64 ns |      4 KB |
|        SetValueMethod |               Manual |      1000 | 6,308.1 ns | 17.87 ns |     27 KB |
|                       |                      |           |            |          |           |
|        ListCollection | Populated Collection |      1000 |   131.5 ns |  1.22 ns |      4 KB |
|           ArrayCopyTo | Populated Collection |      1000 |   131.6 ns |  0.88 ns |      4 KB |
|            LinqConcat | Populated Collection |      1000 |   192.8 ns |  1.07 ns |      4 KB |

From the result, we can clearly see that the ArrayIndexInitializer approach is faster than the SetValue method.

The populated collection group is faster though with pretty similar results.

Benchmark With 10,000 Elements

Now, let’s run the same benchmark for an array size of 10,000 and look for the result:

|                Method |           Categories | arraySize |      Mean |     Error | Allocated |
|---------------------- |--------------------- |---------- |----------:|----------:|----------:|
| ArrayIndexInitializer |               Manual |     10000 |  2.942 us | 0.0181 us |     39 KB |
|        SetValueMethod |               Manual |     10000 | 63.253 us | 0.4825 us |    273 KB |
|                       |                      |           |           |           |           |
|           ArrayCopyTo | Populated Collection |     10000 |  1.641 us | 0.0139 us |     39 KB |
|        ListCollection | Populated Collection |     10000 |  1.656 us | 0.0204 us |     39 KB |
|            LinqConcat | Populated Collection |     10000 |  1.834 us | 0.0119 us |     39 KB |

We can see that the mean increases almost proportionately to the array size.

Conclusion

In this article, we’ve learned how to add values to a C# array. Later, we compared the performance of the different approaches and finally came to know that the array index initialization is the fastest approach.

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Become a patron at Patreon!