views:

250

answers:

7

Duplicate

Array of Unknown Length in C#

How do I initialize string[] without a need of initializing the length? I want it to be dynamic array, so when I add something, Length increases and no Exception raises?

Should I just use some kind of List?

+1  A: 

I think a lot of languages out there will allocate the entire array as a block up front. You may need to use a wrapper class that provides this functionality. In the absence of a language specified, Java and C++ for example, int[] will be a contiguous block of memory. You'll have to allocate a new block and copy the old contents, or use a wrapper that manages this for you, either doing the same thing or using pointers to objects. That would be ArrayList or similar in Java.

John Ellinwood
A: 

If your using C# use ArrayList. It dynamically expands as you need it and it also can hold anything (this can be both good and bad). So yes you should use some kind of list. Also remember to include this using statement:

using System.Collections;
Lucas McCoy
List<string> would be a better option than ArrayList, if you're using C#2 or higher.
LukeH
Yes, no reason for ArrayList anymore.
Ed Swangren
+1  A: 

Arrays have a fixed length in most languages. You have to use a dynamic datatype like a list if you need dynamic length.

If the language does not suport lists natively, they are usually implemented with arrays. If the content becomes to long to fit into the array, a longer array is allocated, the content copied from the old array to the new one, and finally the old array is freed.

I am quite sure there is a dynamic length type in your language or one of its libraries.

UPDATE

For C# the collection classes are found in the System.Collections namespace. You should focus on the generic classes in System.Collections.Generic if possible. Four your case the generic List<String> would probably fit best. But also Stack<String> or Queue<String> might be interesting.

Daniel Brückner
+1  A: 

What language?

C#, Java, and many other high-level languages have ArrayList data structure (or something similar) that allow you to add and remove elements without setting a specific size.

Aziz
+1  A: 

Well, in fortran you could use ALLOCATE.

ldigas
+6  A: 

If you need to have an array of unkown length of strings, use a List<T> from the System.Collections.Generic namespace.

List<string> myList = new List<string>();
myList.Add("First");
myList.Add("Second");
myList.Add("Third");
myList.Count // = 3

This uses an array behind the scenes that is of a fixed size, but it hides the fact that it will make the array bigger and move all elements when it runs out of space.

Samuel
+3  A: 

List<T> will do what you want. This has a ToArray() method that will return an array when you're done adding items (if you still need an array).

Jon B