tags:

views:

371

answers:

5

noob question on c#: how to create a one-dimensional dynamic array? And how to change it later?

thanks.

+3  A: 

Sure sounds like you should look into List<T> instead.

gbogumil
+11  A: 

Instead of using an array, you can use the List<> object in C#.

List<int> integerList = new List<int>();

To iterate on items contained in the list, use the foreach operator :

foreach(int i in integerList)
{
    // do stuff with i
}

You can add items in the list object with Add() and Remove() functions.

for(int i = 0; i < 10; i++)
{
    integerList.Add(i);
}

integerList.Remove(6);
integerList.Remove(7);

You can convert a List<T> to an array using the ToArray() function :

int[] integerArray = integerList.ToArray();

Here is the documentation on List<> object.

Thibault Falise
I would add that if you need an array as output, you can then call .ToArray() on your list after you have finished processing it.
Paddy
Make sure `using System.Linq` is included for Paddy's idea to work.
Callum Rogers
@Callum : Linq is not required to use the ToArray function.
Thibault Falise
Oops, sorry, my mistake. It is for IEnumerable<T> though.
Callum Rogers
Not even, I'm working and .Net 2.0 and I can use IEnumerable<T> and ToArray()
Thibault Falise
A: 

use either:

ArrayList  //really you should avoid this.
or List<T>

so

var my_list = new List<Your_List_Type_Here>() (Like List<String>);

This way to add you just do:

my_list.Add(Your_Object);

Link to Generic List: http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx

if you want to go back to an array then just call the ToArray() method.

Kevin
A: 

Arrays are not dynamic. If you want something dynamic use a 'List<T>' or some other collection. You can always call the ToArray() method on it to get an array back.

Dan Diplo
A: 

As others have mentioned, a List<T> is likely what you want. But for completeness, you can resize an array using the Array.Resize static method. Example:

int[] array = { 1, 2, 3 };
Array.Resize(ref array, 4);
Anthony Pegram