OneBite.Dev - Coding blog in a bite size

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

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

Manipulating arrays is a fundamental skill in most programming languages, including C#. This article will focus on how to add an element at the beginning of an array in this language.

Code snippet: Inserting an Element at the Beginning of an Array

Here’s an example of how an element is inserted at the beginning of an array in C#.

using System;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] nums = new[] { 2, 3, 4, 5 };
        int newValue = 1;

        nums = new[] { newValue }.Concat(nums).ToArray();

        foreach (int num in nums)
        {
            Console.WriteLine(num);
        }
    }
}

This code snippet will output: 1, 2, 3, 4, 5.

Code Explanation: Inserting an Element at the Beginning of an Array

Let’s break down what the code does:

  • First, the initial elements of the array are defined:
 int[] nums = new[] { 2, 3, 4, 5 };

This line declares and initializes an integer array ‘nums’.

  • Next, the new value to be inserted is defined:
int newValue = 1;

This line declares and sets the new value ‘newValue’ which is intended to be inserted at the start of the array.

  • We then recreate the array by concatenating ‘newValue’ to the original array:
nums = new[] { newValue }.Concat(nums).ToArray();

In this line, ‘newValue’ is placed into a new array and concatenated with ‘nums’ using the ‘Concat()’ function. The result is then converted back into an array and stored in ‘nums’. This effectively inserts ‘newValue’ at the start of the array.

  • The updated array is then printed to the console using a foreach loop:
foreach (int num in nums)
{
    Console.WriteLine(num);
}

This loop iterates through each element of the ‘nums’ array and prints it to the console, confirming that ‘newValue’ has been successfully inserted at the start of the array.

c-sharp