How can I dynamically create an array in C#?
Asked
Active
Viewed 6.2k times
7 Answers
22
I'd like to add to Natrium's answer that generic collections also support this .ToArray() method.
List<string> stringList = new List<string>();
stringList.Add("1");
stringList.Add("2");
stringList.Add("3");
string[] stringArray = stringList.ToArray();
Gerrie Schenck
- 21,820
- 19
- 67
- 95
-
1As a note, they support ToArray() because internally, list is just plain using an immutable array and growing it with new allocations as needed. – Dec 07 '14 at 10:50
8
First make an arraylist. Add/remove items. And then ArrayList.ToArray()
And there is your array!
Natrium
- 29,961
- 15
- 57
- 72
6
Ok so array initialisation gets me every single time. so I took 10 minutes to do this right.
static void Main(string[] args)
{
String[] as1 = new String[] { "Static", "with", "initializer" };
ShowArray("as1", as1);
String[] as2 = new String[5];
as2[0] = "Static";
as2[2] = "with";
as2[3] = "initial";
as2[4] = "size";
ShowArray("as2", as2);
ArrayList al3 = new ArrayList();
al3.Add("Dynamic");
al3.Add("using");
al3.Add("ArrayList");
//wow! this is harder than it should be
String[] as3 = (String[])al3.ToArray(typeof(string));
ShowArray("as3", as3);
List<string> gl4 = new List<string>();
gl4.Add("Dynamic");
gl4.Add("using");
gl4.Add("generic");
gl4.Add("list");
//ahhhhhh generic lubberlyness :)
String[] as4 = gl4.ToArray();
ShowArray("as4", as4);
}
private static void ShowArray(string msg, string[] x)
{
Console.WriteLine(msg);
for(int i=0;i<x.Length;i++)
{
Console.WriteLine("item({0})={1}",i,x[i]);
}
}
Michael Dausmann
- 3,655
- 2
- 32
- 44
5
object foo = Array.CreateInstance(typeof(byte), length);
SgtOJ
- 499
- 1
- 9
- 23
Matthew Flaschen
- 268,153
- 48
- 509
- 534
1
You can also use the new operator just like with other object types:
int[] array = new int[5];
or, with a variable:
int[] array = new int[someLength];
Bojan Resnik
- 7,202
- 27
- 29
-
10
-
-
once defined, you will need to re-initiate the array in order to add more than 5 items – Natrium May 19 '09 at 09:44
-
3That's correct - however, the OP asked about dynamic creation of arrays, not necessarily about the ability to dynamically grow an array. – Bojan Resnik May 19 '09 at 10:55
-1
int[] array = { 1, 2, 3, 4, 5};
for (int i=0;i<=array.Length-1 ;i++ ) {
Console.WriteLine(array[i]);
}
Jan Doggen
- 8,537
- 13
- 64
- 132
sina rezaei
- 1
- 1