How is an array of strings where you do not know the array size in C#/.NET declared?
String[] array = new String[]; // this does not work
How is an array of strings where you do not know the array size in C#/.NET declared?
String[] array = new String[]; // this does not work
Is there a specific reason why you need to use an array? If you don't know the size before hand you might want to use List<String>
List<String> list = new List<String>();
list.Add("Hello");
list.Add("world");
list.Add("!");
Console.WriteLine(list[2]);
Will give you an output of
!
MSDN - List(T) for more information
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 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 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];
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.
You should use a List<>. But you can do the following:
string[] strings = { };
strings = strings.Append("Hello").ToArray();
strings = strings.Append("world").ToArray();
strings = strings.Append("!").ToArray();
Console.WriteLine($"{strings[0]} {strings[1]} {strings[2]}");
//Prints: Hello world!
Although it works you really should use other dynamically scaling data structure. Only use arrays when the size is known beforehand.
string foo = "Apple, Plum, Cherry";
string[] myArr = null;
myArr = foo.Split(',');