Arrays resized dynamically



In C#, arrays cannot be resized dynamically. One approach is to use System.Collections.ArrayList instead of a native array. Another (faster) solution is to re-allocate the array with a different size and to copy the contents of the old array to the new array. The generic function resizeArray (below) can be used to do that.
Example is bellow


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


How to Test 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;a++)
   {
         System.Console.WriteLine ("Aarray of  "+i+" is "+a[i]);
}

Aarray of  0 is1
Aarray of 1 is 2
Aarray of 2 is 3
Aarray of 3 is 4
Aarray of 4 is5

No comments:

Post a Comment