change array size change array size arrays arrays

change array size


You can use Array.Resize(), documented in MSDN.

But yeah, I agree with Corey, if you need a dynamically sized data structure, we have Lists for that.

Important: Array.Resize() doesn't resize the array (the method name is misleading), it creates a new array and only replaces the reference you passed to the method.

An example:

var array1 = new byte[10];var array2 = array1;Array.Resize<byte>(ref array1, 20);// Now:// array1.Length is 20// array2.Length is 10// Two different arrays.


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.


You can use Array.Resize() in .net 3.5 and higher. This method allocates a new array with the specified size, copies elements from the old array to the new one, and then replaces the old array with the new one.(So you will need the memory available for both arrays as this probably uses Array.Copy under the covers)