Add Or Append Item To An Array C#

Sameer Saini March 06, 2022
Add Or Append Item To An Array C#

In this post, we will add to an array in C#.

Adding element to array means to add a new item or an element of type to an existing array.

In C#, we have a few different options to add or append to an existing array.

Let's see all of these with examples.

 

 

 

Add To Array Using Array.Append() Method C#

The .Append() method on the array appends a value to the end of the sequence.

 

Syntax:

Append(this IEnumerable source, TSource element)

 

Return:

The Array.Append() method returns a new sequence that ends with element.

IEnumerable

 

Array.Append() Method - Code Example

// New String Array with a few default values string[] colorsArray = new string[] { "Red", "Blue" }; // Using the .Append() method and converting it back to a string array colorsArray = colorsArray.Append("Yellow").ToArray(); // Display values foreach (var item in colorsArray) { Console.WriteLine(item); }

Output:

Red Blue Yellow

 

 

 

Add Element To Array Using Array.Resize() Method C#

Using the .Resize() method on the array, we can resize the size of the array. We can resize the original array to a bigger size so that we can add or append elements to that array.

The .Resize() method changes the number of elements of a one-dimensional array to the specified new size.

 

Syntax:

Resize([NotNull] ref T[]? array, int newSize)

 

Array.Resize() Method - Code Example

// New String Array with a few default values string[] colorsArray = new string[] { "Red", "Blue" }; // We will resize the original array and increase the length by 1 Array.Resize(ref colorsArray, colorsArray.Length + 1); // Adding a new element by adding a new item on the last element colorsArray[colorsArray.Length - 1] = "Orange"; // Display values foreach (var item in colorsArray) { Console.WriteLine(item); }

Output:

Red Blue Orange

 

 

Add Element To Array By Converting Array To List And Using List.Add() Method C#

In this example, we will first convert the array to a list and then use the .Add() method on the list to add an item to the end of the list. Then we will convert back this list to an array if required.

 

Syntax:

Add(T item)

 

List.Add() Method - Code Example

// New String Array with a few default values string[] colorsArray = new string[] { "Red", "Blue" }; // Convert Array To List var colorsList = colorsArray.ToList(); // Add Item To List colorsList.Add("White"); // Convert back to List colorsArray = colorsList.ToArray(); // Display values foreach (var item in colorsArray) { Console.WriteLine(item); }

Output:

Red Blue White