The approach closest to what you are describing is to use the Array.Copy
method:
string[] arrColumns = new string[1024];
string[] newArray = new string[arrColumns.Length + 1];
Array.Copy(arrColumns, 0, newArray, 1, arrColumns.Length);
newArray[0] = "Hello, world!
This is a little long winded, especially if you keep doing this. A better option is to not worry about the details of copying and inserting a value in the first position, by using a List<T>
and go from there.
There are 3 options to improve this:
- Use a
List<T>
with a capacity
- Use a
List<T>
with the original array
- Create a
List<T>
from the existing array
Use a List<T>
with a capacity
Use the List<string>
that accepts a capacity in the constructor, so that you give it a heads up (where possible) on the size to create.
It will then allocate the initial size internally, but still know the number of items stored in the .Count
, rather than the .Capacity
. It is also dynamically expanding:
List<string> listOfColumns = new List<string>(1024); // Set initial capacity
listOfColumns.Add( .... );
Use a List<T>
with the original array
Another alternative is to just pass the array directly into the constructor, and you can use the overload to pass an existing array in:
List<string> listOfColumns = new List<string>(arrColumns);
Create a List<T>
from the existing array
Use the System.Linq extension to create a List<T>
automatically:
List<string> listOfColumns = arrColumns.ToList();
Then you can insert an item into the beginning of the list.
listOfColumns.Insert(0, "Hello, World!");
To get the data as an array, use the .ToArray()
method.
string[] arrColumns = listOfColumns.ToArray();