JavaScript Array push() The push() method adds new items to the end of an array. The push() method changes the length of the array. The push() method returns the new length.
We can insert the elements wherever we want, which means we can insert either at starting position or at the middle or at last or anywhere in the array. After inserting the element in the array, the positions or index location is increased but it does not mean the size of the array is increasing.
I would use a List if you need a dynamically sized array:
List<string> ls = new List<string>();
ls.Add("Hello");
That could be a solution;
Array.Resize(ref array, newsize);
array[newsize - 1] = "newvalue"
But for dynamic sized array I would prefer list too.
Using LINQ:
arr = (arr ?? Enumerable.Empty<string>()).Concat(new[] { newitem }).ToArray();
I like using this as it is a one-liner and very convenient to embed in a switch statement, a simple if-statement, or pass as argument.
EDIT:
Some people don't like new[] { newitem }
because it creates a small, one-item, temporary array. Here is a version using Enumerable.Repeat
that does not require creating any object (at least not on the surface -- .NET iterators probably create a bunch of state machine objects under the table).
arr = (arr ?? Enumerable.Empty<string>()).Concat(Enumerable.Repeat(newitem,1)).ToArray();
And if you are sure that the array is never null
to start with, you can simplify it to:
arr.Concat(Enumerable.Repeat(newitem,1)).ToArray();
Notice that if you want to add items to a an ordered collection, List
is probably the data structure you want, not an array to start with.
Very old question, but still wanted to add this.
If you're looking for a one-liner, you can use the code below. It combines the list constructor that accepts an enumerable and the "new" (since question raised) initializer syntax.
myArray = new List<string>(myArray) { "add this" }.ToArray();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With