8

How can I dynamically create an array in C#?

SgtOJ
  • 569
  • 2
  • 10
  • 23
saurabh
  • 271
  • 1
  • 6
  • 18

7 Answers7

24

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
  • 22,148
  • 20
  • 68
  • 95
  • 1
    As 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
  • 30,772
  • 17
  • 59
  • 73
7
object foo = Array.CreateInstance(typeof(byte), length);
SgtOJ
  • 569
  • 2
  • 10
  • 23
Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
7

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
  • 4,202
  • 3
  • 35
  • 48
2

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,320
  • 28
  • 29
-1
int[] array = { 1, 2, 3, 4, 5};

for (int i=0;i<=array.Length-1 ;i++ ) {
  Console.WriteLine(array[i]);
}
Jan Doggen
  • 8,799
  • 13
  • 70
  • 144
-1

Use generic List or ArrayList.

blitzkriegz
  • 9,258
  • 18
  • 60
  • 71