How to resize an array in C#
In C#, arrays cannot be resized dynamically. One approach is to use System.Collections.ArrayList instead of a native array. Another solution is to re-allocate the array with a different size and copy the content of the old array to the new array.
public static void Main() { int[] a1 = {1, 2, 3}; int[] a2 = a1; a2[0] = 55; // this also modifies a1[0] System.Array.Resize(ref a1, 5); // this only modifies a1, not a2 a2[0] = 66; // this only modifies a2[0], not a1[0] // a1 now points to the new array which has length 5. System.Console.WriteLine("a1.Length=" + a1.Length); for (int i = 0; i < a1.Length; i++) { System.Console.WriteLine("a1[" + i + "]=" + a1[i]); } // a2 still points to the old array with length 3. System.Console.WriteLine("a2.Length=" + a2.Length); for (int i = 0; i < a2.Length; i++) { System.Console.WriteLine("a2[" + i + "]=" + a2[i]); } }
// Reallocates an array with a new size, and copies the contents // of the old array to the new array. // Arguments: // oldArray the old array, to be reallocated. // newSize the new array size. // Returns A new array with the same content. public static System.Array ResizeArray (System.Array oldArray, int newSize) { int oldSize = oldArray.Length; System.Type elementType = oldArray.GetType().GetElementType(); System.Array newArray = System.Array.CreateInstance(elementType, newSize); int preserveLength = System.Math.Min(oldSize, newSize); if (preserveLength > 0) { System.Array.Copy (oldArray, newArray, preserveLength); } return newArray; }
// Test routine for ResizeArray(). public static void Main () { int[] a = {1, 2, 3}; a = (int[])ResizeArray(a, 5); a[3] = 4; a[4] = 5; for (int i = 0; i < a.Length; i++) { System.Console.WriteLine(a[i]); } }
Author: Christian d'Heureuse (www.source-code.biz, www.inventec.ch/chdh)
License: Free / LGPL
Index