OneBite.Dev - Coding blog in a bite size

Append Item In Array In C#

Code snippet for how to Append Item In Array In C# with sample and detail explanation

In this article, we’ll be talking about appending items to an array in C#. This is a fairly common operation and having a better understanding of it can improve your skills in writing C#.

Code snippet for Appending Items in Array

Here’s a simple code snippet of how to append items to an array in C#:

using System;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] array = {1, 2, 3};
        array = AppendToArray(array, 4);
        foreach (var item in array) {
            Console.WriteLine(item);
        }
    }
    static int[] AppendToArray(int[] array, int item)
    {
        array = array.Concat(new[] {item}).ToArray();
        return array;
    }
}

This code will output:

1
2
3
4

Code Explanation for Appending Items in Array

In this tutorial, we’ll break down what happens in this code step by step.

  1. First, we declare and initialize an array that houses three integer values: {1, 2 ,3}.
int[] array = {1, 2, 3};
  1. Then we call the AppendToArray() function, passing our array and the value we want to append, which is 4. This function will return a new array with appended values.
array = AppendToArray(array, 4);
  1. Let’s look at the AppendToArray() function. It takes two parameters—a integer array and an integer item we want to add to the array.
static int[] AppendToArray(int[] array, int item)
  1. Inside the function, we use the Concat() method, a Linq method which is used to concatenate or link two sequences. Then we convert the result to an array using ToArray().
array = array.Concat(new[] {item}).ToArray();
  1. We then return the result, i.e., initial array with the new item appended to it.
return array;
  1. Finally, we use a foreach loop to print out every item in our updated array.
foreach (var item in array) {
    Console.WriteLine(item);
}

Implicit in C#, arrays are fixed in size and cannot be resized once created. We get around this by creating a new array that includes the original array elements plus the new item. This is a very common technique when we need to append items to an array in C#.

c-sharp