C# Array Resize

Description

Array Resizechanges the number of elements of a one-dimensional array to the specified new size.

Syntax

Array.Resize has the following syntax.


public static void Resize<T>(
  ref T[] array,
  int newSize
)

Parameters

Array.Resize has the following parameters.

  • T - The type of the elements of the array.
  • array - The one-dimensional, zero-based array to resize, or null to create a new array with the specified size.
  • newSize - The size of the new array.

Returns

Array.Resize method returns

Example

The following code illustrates one possible implementation for a method that resizes an array of n dimensions.


using System;//from  w w w  . j  a  v  a2s  . c o m

public class Example
{
   public static void Main()
   {
      int[,] arr = new int[10,2];
      // Make a 2-D array larger in the first dimension.
      arr = (int[,]) ResizeArray(arr, new int[] { 12, 2} );
      // Make a 2-D array smaller in the first dimension.
      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;
   }   
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version