remove an element from the end of an array in csharp

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.cs
int[] numbers = { 1, 2, 3, 4, 5 };
Array.Resize(ref numbers, numbers.Length - 1);
82 chars
3 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.cs
int[] numbers = { 1, 2, 3, 4, 5 };
List<int> list = numbers.ToList();
list.RemoveAt(list.Count - 1);
numbers = list.ToArray();
127 chars
5 lines

This code removes the last element from the numbers array using a list as an intermediary step.

gistlibby LogSnag