Mono Class Library: System.Array Overview | Members

System.Array.CreateInstance Method

Creates a zero-based, multidimensional array of the specified Type and dimension lengths. [Edit]

public static Array CreateInstance (Type elementType, params int[] lengths)

Parameters

elementType
The Type of the elements contained in the new Array instance. [Edit]
lengths
A one-dimensional array of int objects that contains the size of each dimension of the new Array instance. [Edit]

Returns

A new zero-based, multidimensional Array instance of the specified Type with the specified length for each dimension. The Array.Rank of the new instance is equal to lengths.Length. [Edit]

Exceptions

TypeReason
ArgumentNullExceptionelementType or lengths is null. [Edit]
ArgumentException

elementType is not a valid Type.

-or-

lengths.Length = 0.

[Edit]
ArgumentOutOfRangeExceptionA value in lengths is less than zero. [Edit]

Remarks

The number of elements in lengths is required to equal the number of dimensions in the new Array instance. Each element of lengths specifies the length of the corresponding dimension in the new instance.

Reference-type elements will be set to null. Value-type elements will be set to zero, except for bool elements, which will be set to false.

Note: Unlike most classes, Array provides the Array.CreateInstance(Type, int) method, instead of public constructors, to allow for late bound access.

[Edit]

Example

The following example shows how to create and initialize a multidimensional Array.

C# Example
using System;

public class CreateMultiDimArrayExample
{
   public static void Main()
   {
      int i, j, k;
      int[] indexAry = {2, 4, 5};
      Array ary = Array.CreateInstance( typeof(int), indexAry );
      for( i = ary.GetLowerBound(0); i <= ary.GetUpperBound(0); i++ )
      {
         for( j = ary.GetLowerBound(1); j <= ary.GetUpperBound(1); j++ )
         {
            for( k = ary.GetLowerBound(2); k <= ary.GetUpperBound(2); k++ )
            {
               ary.SetValue( (100*i + 10*j + k), i, j, k );
            }
         }
      }
      Console.WriteLine("The elements of the array are:");
      for( i = ary.GetLowerBound(0); i <= ary.GetUpperBound(0); i++)
      {
         for( j = ary.GetLowerBound(1); j <= ary.GetUpperBound(1); j++)
         {
             for( k = ary.GetLowerBound(2); k <= ary.GetUpperBound(2); k++ )
            {
               Console.Write("{0, 3} ", ary.GetValue(i, j, k));
            }
            Console.WriteLine();
         }
         Console.WriteLine();
      }
   }
}
   

The output is

Example
The elements of the array are:
  0   1   2   3   4
 10  11  12  13  14
 20  21  22  23  24
 30  31  32  33  34

100 101 102 103 104
110 111 112 113 114
120 121 122 123 124
130 131 132 133 134 

Requirements

Namespace: System
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0