Search code examples
c#arrayssize

change array size


Is it possible to change an array size after declaration? If not, is there any alternative to arrays?
I do not want to create an array with a size of 1000, but I do not know the size of the array when I'm creating it.


Solution

  • No, try using a strongly typed List instead.

    For example:

    Instead of using

    int[] myArray = new int[2];
    myArray[0] = 1;
    myArray[1] = 2;
    

    You could do this:

    List<int> myList = new List<int>();
    myList.Add(1);
    myList.Add(2);
    

    Lists use arrays to store the data so you get the speed benefit of arrays with the convenience of a LinkedList by being able to add and remove items without worrying about having to manually change its size.

    This doesn't mean an array's size (in this instance, a List) isn't changed though - hence the emphasis on the word manually.

    As soon as your array hits its predefined size, the JIT will allocate a new array on the heap that is twice the size and copy your existing array across.