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.cs324 chars17 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