How to Insert an element at a specific position in an Array in C#?

QuestionsCategory: C#How to Insert an element at a specific position in an Array in C#?
Himanshu SHimanshu S asked 1 year ago

Given an array wanted to insert item into 2nd position

var arr1 = new[] { "Cat", "Monkey", "Dog" };
2 Answers
Mahesh DeshmaneMahesh Deshmane answered 1 year ago

As array element cannot be resized automatically so, of you want insert an element at a specific position in an Array then you have to resize the array then proceed. You could convert this array to List or ArrayList then insert the element to it.
Using List.Insert:

var arr1 = new[] { "Cat", "Monkey", "Dog" };

var result = arr1.ToList();

result.Insert(2, "Cheetah");

//Output "Cat", "Monkey", "Cheetah", "Dog"

Below is code without using List option.

var index = 2;
string value = "Cheetah";

var arr1 = new[] { "Cat", "Monkey", "Dog" };

var result = new string[arr1.Length + 1];

Array.Copy(arr1, 0, result, 0, index);
result[index] = value;
var pos = index;

for (var j = index; j < arr1.Length; j++)
{
    result[++pos] = arr1[j];
}
Zayed al MansouriZayed al Mansouri answered 9 months ago

Greatly explained Mr Mahesh Deshmane, It seems like you are good at your work, we would like you to have on board. We are Cheap Assignment Writing Services UAE as we provide assignment services to students across UAE and Gulf countries and we have been doing it since 2015 with the capacity of more than 500 expert and professional writers from UAE.