insert an element into an array at a specific index in csharp

To insert an element into an array at a specific index in C#, you can make use of the Array.Copy method. The steps to achieve this are as follows:

  1. Create a new array that is one element larger than the original array.
  2. Use the Array.Copy method to copy the elements from the original array to the new array up to the specified index.
  3. Insert the new element at the specified index in the new array.
  4. Use the Array.Copy method to copy the remaining elements from the original array to the new array starting from the specified index.

Here's an example code snippet that demonstrates this:

main.cs
string[] originalArray = { "element1", "element2", "element4" };
string newElement = "element3";
int insertIndex = 2;

string[] newArray = new string[originalArray.Length + 1];
Array.Copy(originalArray, 0, newArray, 0, insertIndex);
newArray[insertIndex] = newElement;
Array.Copy(originalArray, insertIndex, newArray, insertIndex + 1, originalArray.Length - insertIndex);

// The newArray now contains "element1", "element2", "element3", "element4"
449 chars
11 lines

In this example, we are inserting the element "element3" at index 2 in the original array. The resulting newArray contains all the elements from the original array, with the new element inserted at the specified index.

gistlibby LogSnag