8

How can I dynamically create an array in C#?

2
  • 3
    What do you mean by that? Please show some pseudocode of what you are trying. Commented May 19, 2009 at 5:51
  • 1
    Do you mean that you should be able to resize the array? Commented May 19, 2009 at 6:21

7 Answers 7

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();
Sign up to request clarification or add additional context in comments.

1 Comment

As a note, they support ToArray() because internally, list is just plain using an immutable array and growing it with new allocations as needed.
8

First make an arraylist. Add/remove items. And then ArrayList.ToArray()

And there is your array!

Comments

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]);
        }
    }

Comments

7
object foo = Array.CreateInstance(typeof(byte), length);

Comments

3

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

This is not quite dynamic is it?
Why not? You can use a variable instead of a literal 5 there.
once defined, you will need to re-initiate the array in order to add more than 5 items
That's correct - however, the OP asked about dynamic creation of arrays, not necessarily about the ability to dynamically grow an array.
-1

Use generic List or ArrayList.

Comments

-1
int[] array = { 1, 2, 3, 4, 5};

for (int i=0;i<=array.Length-1 ;i++ ) {
  Console.WriteLine(array[i]);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.