How can I dynamically create an array in C#?
-
3What do you mean by that? Please show some pseudocode of what you are trying.shahkalpesh– shahkalpesh2009-05-19 05:51:17 +00:00Commented May 19, 2009 at 5:51
-
1Do you mean that you should be able to resize the array?blitzkriegz– blitzkriegz2009-05-19 06:21:26 +00:00Commented May 19, 2009 at 6:21
Add a comment
|
7 Answers
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();
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]);
}
}
Comments
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];
4 Comments
Gerrie Schenck
This is not quite dynamic is it?
Bojan Resnik
Why not? You can use a variable instead of a literal 5 there.
Natrium
once defined, you will need to re-initiate the array in order to add more than 5 items
Bojan Resnik
That's correct - however, the OP asked about dynamic creation of arrays, not necessarily about the ability to dynamically grow an array.