noob question on c#: how to create a one-dimensional dynamic array? And how to change it later?
thanks.
noob question on c#: how to create a one-dimensional dynamic array? And how to change it later?
thanks.
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.
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.
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);