OneBite.Dev - Coding blog in a bite size

Insert An Element At A Specific Index In An Array In C#

Code snippet for how to Insert An Element At A Specific Index In An Array In C# with sample and detail explanation

Inserting an Element at a Specific Index in an Array in C# is a fundamental skill that every software developer must acquire. This article will provide a tutorial on how to embed an element at a particular index in an array utilizing C#.

Code Snippet to Insert an Element at a Specific Index in an Array

using System;

public class Program
{
    public static void Main()
    {
        int[] oldArray = {1, 2, 3, 4, 5};
        int index = 2;
        int value = 6;

        int[] newArray = new int[oldArray.Length + 1];
        
        for(int i = 0; i < newArray.Length; i++)
        {
            if(i < index)
                newArray[i] = oldArray[i];
            else if(i == index)
                newArray[i] = value;
            else
                newArray[i] = oldArray[i-1];
        }

        Console.WriteLine("New array: " + string.Join(",", newArray));
    }
}

Code Explanation for Inserting an Element at a Specific Index in an Array

This code snippet is a simple program for adding a value at a specific index in an array.

Firstly, we declare our original integer array known as ‘oldArray’ and also our index at which we want to insert the new element and the value that we want to insert.

Next, we declare ‘newArray’ with a size one element larger than that of our ‘oldArray’, as we will be adding an element.

Now comes the main part. We use a ‘for’ loop to iterate over each element in the ‘newArray’. If the index of ‘newArray’ element is less than the desired index, we simply copy the values from ‘oldArray’ to ‘newArray’.

When we reach the desired index, we insert our new value, without copying anything from the ‘oldArray’. Now we have an array that has one more element than our ‘oldArray’ and also includes the new element at the desired index.

The last part is to copy the remaining values from ‘oldArray’ to ‘newArray’, starting from the position after the new added element in ‘newArray’.

Finally, the console displays our ‘newArray’ with the new value inserted at the specified index. This method effectively inserts a value at a particular index of an array in C#.

c-sharp