

Different Ways to Add Values to a C# Array
source link: https://code-maze.com/add-values-to-csharp-array/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Different Ways to Add Values to a C# Array

We value your privacy
Want to build great APIs? Or become even better at it? Check our Ultimate ASP.NET Core Web API program and learn how to create a full production-ready ASP.NET Core API using only the latest .NET technologies. Bonus materials (Security book, Docker book, and other bonus files) are included in the Premium package!
In this article, we are going to learn about the different ways we can add values to a C# array.
Let’s dive in.
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.
Array 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
).
Array.SetValue() Method
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.
Array.CopyTo() Method
One more approach to add 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.
Array.Resize() Method
While we won’t use this method in the benchmark since it doesn’t add values to the array, it’s important to know how to use it because it is a part of adding values to the array in some cases.
Using the Array.Resize()
method, we can change the size of an array and then add values to it. We can either increase or decrease an array size using this method.
Let’s say, we have an empty array:
var array = Array.Empty<int>();
In order to resize this array to hold 3 elements, we can simply do:
Array.Resize(ref array, 3);
Here, we are passing the reference to an array using the ref
keyword as the first parameter and the new array size as the second parameter.
After that, we can use one of the existing ways of adding values to an array in C#.
Add Values to a C# Array by Using Lists
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
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.
LINQ Append() Method
Another approach to adding values to an array is to use the Append()
method in LINQ. Using this method, we can add values to the end of the sequence.
Let’s create a simple empty array:
var array = Array.Empty<int>();
Now, let’s append the values using the Append()
method:
array = array.Append(100).ToArray();
Here, the Append()
method returns IEnumerable<T>
. But, if we want an array, we can convert it back using the ToArray()
method.
In case we want to add an element at the start of the sequence, we need to use Prepend()
method.
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 benchmark:
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.
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 | arraySize | Mean | Error | StdDev | Median | |--------------------- |---------- |----------------:|--------------:|----------------:|----------------:| | ArrayIndexInitializer| 1000 | 542.5 ns | 6.13 ns | 5.43 ns | 542.3 ns | | ListCollection | 1000 | 2,151.2 ns | 42.14 ns | 64.36 ns | 2,141.9 ns | | ArrayCopyTo | 1000 | 2,181.7 ns | 43.36 ns | 51.62 ns | 2,170.3 ns | | LinqConcat | 1000 | 2,474.5 ns | 16.86 ns | 13.16 ns | 2,474.2 ns | | SetValueMethod | 1000 | 14,316.8 ns | 268.95 ns | 251.57 ns | 14,356.2 ns | | LinqAppend | 1000 | 172,341.2 ns | 3,399.26 ns | 8,402.14 ns | 168,804.7 ns |
From the result, we can clearly see that the ArrayIndexInitializer
approach is the fastest with a mean of 542.5 ns for an array size of 1,000.
And then, the ListCollection
approach is ~4 times slower with a mean of 2,151.2 ns. The ArrayCopyTo
approach is almost close to the ListCollection
with a mean of 2,181.7 ns.
Surprisingly, the SetValueMethod
approach is ~26 times slower than the index initializer approach with a mean of 14,316.8 ns.
The slowest of all approaches is the LinqAppend
approach which is almost ~317 times slower than the index initializer approach. It clearly shows that this approach is not suitable when we want to append a large number of elements to an array.
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 | arraySize | Mean | Error | StdDev | Median | |--------------------- |---------- |----------------:|--------------:|----------------:|----------------:| | ArrayIndexInitializer| 10000 | 4,062.3 ns | 60.70 ns | 53.81 ns | 4,042.3 ns | | LinqConcat | 10000 | 21,042.1 ns | 231.71 ns | 216.74 ns | 20,994.9 ns | | ArrayCopyTo | 10000 | 22,281.6 ns | 440.88 ns | 900.61 ns | 22,648.8 ns | | ListCollection | 10000 | 22,483.6 ns | 339.80 ns | 283.75 ns | 22,494.7 ns | | SetValueMethod | 10000 | 149,466.5 ns | 2,852.33 ns | 7,951.17 ns | 146,255.6 ns | | LinqAppend | 10000 | 14,526,846.5 ns | 416,189.86 ns | 1,180,661.37 ns | 14,136,703.1 ns |
We can see that the mean increases almost proportionately to the array size. We can also see that the LinqConcat
approach performs better than ArrayCopyTo
and ListCollection
with the increase in size. ArrayIndexInitializer
remains the winner of this benchmark.
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.
Want to build great APIs? Or become even better at it? Check our Ultimate ASP.NET Core Web API program and learn how to create a full production-ready ASP.NET Core API using only the latest .NET technologies. Bonus materials (Security book, Docker book, and other bonus files) are included in the Premium package!
Share:

Get our free, easy Web API best practices guide
used by 20k+ people to become better web devs.
© Copyright code-maze.com 2016 - 2022
Recommend
-
11
Different ways to sort an array of strings in Swift How to sort an array of strings There are two ways to sort in Swift, The one that mutates the original array and the one that don't. Both of them...
-
7
Find values in an array with duplicate values advertisements I have an array of customer names. This array is full of duplicates, and needs to be...
-
8
How to get specific object values from java & lt; List & gt; and convert to String Array advertisements I need your assistant and he...
-
5
Array.at() Will Change How We Access Array Values in JavaScriptHow to access negative indexes in JavaScript, and how this could change with Array.prototype.at()Photo by
-
8
Calculate the array of values in PHP advertisements I have an array i.e. Array ( [18] => 0.6667 [228] => 0.3333...
-
11
Array_combine with key to only one of table 1 and several values of table 2 advertisements I have 2 arrays: array 1 I want it to be a...
-
5
How to MapReduce collection to join an array of all values in the field containing the array advertisements I have the following schema in t...
-
7
Hi guys!. In this post, we will be looking into the best ways CSS code can be added in React JS or to you React App. Obviously, CSS is crucial in making your app user friendly and visually attractive. These are the different way...
-
10
Different ways to add to the DOM with jQuery advertisements Traditionally Ive been appending HTML content to the page like...
-
6
Different Ways to Print The Elements of an Array in C# Posted by Code Maze | Apr 12, 2022 |
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK