remove an element from an array at a specific index in csharp

To remove an element from an array at a specific index in C#, you can use the built-in Array.Copy method to copy the elements to a new array without the element you want to remove. Here's an example:

main.cs
int[] arr = { 1, 2, 3, 4, 5 };
int indexToRemove = 2;

int[] newArr = new int[arr.Length - 1];

if (indexToRemove > 0)
{
    Array.Copy(arr, 0, newArr, 0, indexToRemove);
}

if (indexToRemove < arr.Length - 1)
{
    Array.Copy(arr, indexToRemove + 1, newArr, indexToRemove, arr.Length - indexToRemove - 1);
}

arr = newArr;
324 chars
17 lines

In this example, we have an integer array with 5 elements (arr). We want to remove the element at index 2 (which is the number 3).

We first create a new integer array of size arr.Length - 1 (since we are removing one element). We then use the Array.Copy method to copy the elements before the index to remove into the new array (if indexToRemove > 0), and the elements after the index to remove into the new array (if indexToRemove < arr.Length - 1).

Finally, we set arr to be equal to newArr, which is the original array with the element removed.

gistlibby LogSnag