views:

133

answers:

5

Does .NET have anything similar to Perl arrays, which are indexed numerically but automatically expand as needed? It would work like this:

var x = new DreamArray<string>();

x[6] = "foo";  // x automatically has 7 elements
x[10] = "bar"; // now it has 11
+7  A: 

Use a List<string> instead of an array. You will have to call List.Add("item") to add to the list though.

Obalix
The documentation on the Generic List can be found here:http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx
Steve Wortham
To add that, a List<string> is literally just a wrapper around a string Array.
Jonathan Allen
@Jonathan: True, but it does not increment when an item is added but increments in chunks, thus providing a better performance.
Obalix
A: 

Lists would be the closest. Just use List()

Chad
But you can't just add to List like: x[5] = "foo"
JoelFan
+1  A: 

Hash Tables & ArrayLists are the first 2 things to come to mind. They're not used exactly the same, though you could use a hashtable in a pretty similar manner.

See C# Collections for usage, examples, and more ideas

Slokun
+4  A: 

No but it could be easily emulated with:

class MagicArray<T> : Dictionary<int, T> {}
Paulo Santos
Nice approach, but you should use `SortedList<int, T>` instead of `Dictionary<int, T>` as it also allows indexed access to the values.
Obalix
@Obalix, Dictionary was the first thing that came to my mind when writing the snippet.
Paulo Santos
+1  A: 

You could easily write your own. You would have to implement the ICollection interface and then aggregate a standard List, etc. But, in the indexer property, if the index is greater than the Capacity, simply change the Capacity property to the appropriate size.

Nick