SoFunction
Updated on 2025-04-06

Methods for dynamically adjusting array size in C#

This article describes the method of dynamically adjusting array size in C#. Share it for your reference. The details are as follows:

Usually, we cannot adjust the length after creating an array, but the Array class provides a static method CreateInstance to create a dynamic array, so we can dynamically adjust the length of the array through it.

namespace ArrayManipulation
{
 Class Program
 {
  static void Main (String[] args)
  {
   int[] arr = new int[]{1,2,3};
   PrintArr(arr);
    arr = (int[])Redim(arr,5);
   PrintArr (arr);
    arr = (int[]) Redim (arr, 2);
   PrintArr (arr);
  )
  public static Array Redim (Array origArray, int desiredSize)
  {
   //determine the type of element
   Type t = ().GetElementType();
    //create a number of elements with a new array of expectations
   //new array type must match the type of the original array
   Array newArray =  (t, desiredSize);
    //copy the original elements of the array to the new array
    (origArray, 0, newArray, 0,  (, desiredSize));
    //return new array
   return newArray;
  }
   //print array
  public static void PrintArr (int[] arr)
  {
   foreach (int x in arr)
   {
     (x + ",");
   }
    ();
  }
 }
}

I hope this article will be helpful to everyone's C# programming.