To remove an element from the end of an array in C#, you can use the Array.Resize
method. This method resizes the array to the specified size and preserves the elements at the beginning of the array. We can pass the current size of the array minus one to remove the last element.
Here's an example:
main.cs82 chars3 lines
After executing this code, the numbers
array will have the last element removed and its size will be reduced by one.
Alternatively, if you want to remove an element at a specific index, you can use the System.Collections.Generic.List<T>
class and its RemoveAt
method. First, convert the array to a list using the ToList
method, then remove the element at the desired index, and finally convert the list back to an array using the ToArray
method.
Here's an example:
main.cs127 chars5 lines
This code removes the last element from the numbers
array using a list as an intermediary step.
gistlibby LogSnag