OneBite.Dev - Coding blog in a bite size

Insert An Element At The End Of An Array In C#

Code snippet for how to Insert An Element At The End Of An Array In C# with sample and detail explanation

Adding elements into an array at a particular position is a simple yet commonly used operation in programming. In C#, it becomes easier. We are going to learn how to effectively insert an element at the end of an array in this powerful language.

Code snippet for inserting an element at the end of an array in C#

To exemplify this operation, take a look at the following code:

static void Main(string[] args)
{
    int[] arr = {1, 2, 3, 4, 5};
    int num = 6;

    arr = insertAtEnd(arr, num);

    foreach (int value in arr)
    {
        Console.WriteLine(value);
    }
}

static int[] insertAtEnd(int[] arr, int num)
{
    int[] newArr = new int[arr.Length + 1];

    for (int i = 0; i < arr.Length; i++)
    {
        newArr[i] = arr[i];
    }

    newArr[arr.Length] = num;

    return newArr;
}

Code Explanation for inserting an element at the end of an array in C#

Now, let’s understand in detail what happens in the code above.

In the Main method, we start by defining an array of integers, arr, and the number num we want to insert at the end of the array. We then call the method insertAtEnd, passing arr and num as parameters. The array is then printed out to the console after the insertion operation.

The method insertAtEnd receives these parameters. We know in advance that our new array will be one element larger than our original array, so we create newArr with a size of arr.Length + 1.

We then use a for loop to copy all the values from our original array to the new array. Within the loop, we directly assign each value from our original array to our new array.

After the for loop is executed, all the elements from the original array arr are copied to the new array newArr, but there is still an extra slot unasigned in our new array, because its size is arr.Length + 1. So, at the index arr.Length, which corresponds to the last position in newArr, we insert our number num.

Finally, newArr is returned and replaces arr in the Main method. This new array is exactly like the original one but with num inserted at the end.

c-sharp