Resize an Array in CSharp

Description

The following code shows how to resize an Array.

Example


//from  w ww  .j  a va  2 s.  co  m
using System;

public class Example
{
   public static void Main()
   {
      int[,] arr = new int[10,2];

      arr = (int[,]) ResizeArray(arr, new int[] { 12, 2} );

      arr = (int[,]) ResizeArray(arr, new int[] { 2, 2} );
   }

   private static Array ResizeArray(Array arr, int[] newSizes)
   {
      if (newSizes.Length != arr.Rank)
         throw new ArgumentException("Not Equals", "newSizes"); 

      var temp = Array.CreateInstance(arr.GetType().GetElementType(), newSizes);
      int length = arr.Length <= temp.Length ? arr.Length : temp.Length;
      Array.ConstrainedCopy(arr, 0, temp, 0, length);
      return temp;
   }   
}




















Home »
  C# Tutorial »
    Data Types »




C# Data Types
Bool
Byte
Char
Decimal
Double
Float
Integer
Long
Short
String
C# Array
Array Example
Byte Array
C# Standard Data Type Format
BigInteger
Complex
Currency
DateTime
DateTimeOffset
DateTime Format Parse Convert
TimeSpan
TimeZone
Enum
Null
tuple
var