[c#] array of string with unknown size

How is an array of string where you do not know where the array size in c#.NET?

String[] array = new String[]; // this does not work

This question is related to c# arrays

The answer is


string[ ] array = {};

// it is not null instead it is empty.


You don't have to specify the size of an array when you instantiate it.

You can still declare the array and instantiate it later. For instance:

string[] myArray;

...

myArray = new string[size];

Can you use a List strings and then when you are done use strings.ToArray() to get the array of strings to work with?


As others have mentioned you can use a List<String> (which I agree would be a better choice). In the event that you need the String[] (to pass to an existing method that requires it for instance) you can always retrieve an array from the list (which is a copy of the List<T>'s inner array) like this:

String[] s = yourListOfString.ToArray();

You can't create an array without a size. You'd need to use a list for that.


string foo = "Apple, Plum, Cherry";

string[] myArr = null;

myArr = foo.Split(',');


I think you may be looking for the StringBuilder class. If not, then the generic List class in string form:

List<string> myStringList = new List<string();
myStringList.Add("Test 1");
myStringList.Add("Test 2");

Or, if you need to be absolutely sure that the strings remain in order:

Queue<string> myStringInOriginalOrder = new Queue<string();
myStringInOriginalOrder.Enqueue("Testing...");
myStringInOriginalOrder.Enqueue("1...");
myStringInOriginalOrder.Enqueue("2...");
myStringInOriginalOrder.Enqueue("3...");

Remember, with the List class, the order of the items is an implementation detail and you are not guaranteed that they will stay in the same order you put them in.


I suppose that the array size if a computed value.

int size = ComputeArraySize();

// Then

String[] array = new String[size]; 

If you want to use array without knowing the size first you have to declare it and later you can instantiate it like

string[] myArray;
...
...
myArray=new string[someItems.count];

you can declare an empty array like below

String[] arr = new String[]{}; // declare an empty array
String[] arr2 = {"A", "B"}; // declare and assign values to an array
arr = arr2; // assign valued array to empty array

you can't assign values to above empty array like below

arr[0] = "A"; // you can't do this

If you will later know the length of the array you can create the initial array like this:

String[] array;

And later when you know the length you can finish initializing it like this

array = new String[42];