add an element to the end of an array in csharp

To add an element to the end of an array in C#, you can use the Array.Resize method. Here's an example:

main.cs
int[] myArray = { 1, 2, 3, 4, 5 };
Array.Resize(ref myArray, myArray.Length + 1);
myArray[myArray.Length - 1] = 6;
115 chars
4 lines

In this example, we first create an array with 5 elements. We then use the Array.Resize method to increase the size of the array by 1. Finally, we assign the value 6 to the last element in the array.

Note that using the Array.Resize method can be inefficient for large arrays, as it requires copying the entire array to a new location in memory. In some cases, using a List or other collection type may be more appropriate.

gistlibby LogSnag