System.Array.CreateInstance Method

Creates a one-dimensional Array of the specified Type and length, with zero-based indexing.

Syntax

public static Array CreateInstance (Type elementType, int length)

Parameters

elementType
The Type of the Array to create.
length
The size of the Array to create.

Returns

A new one-dimensional Array of the specified Type with the specified length, using zero-based indexing.

Exceptions

TypeReason
ArgumentNullException elementType is null.
ArgumentException elementType is not a valid Type.
ArgumentOutOfRangeException length < 0.

Remarks

Unlike most classes, Array provides the erload:System.Array.CreateInstance method, instead of public constructors, to allow for late bound access.

Reference-type elements are initialized to null. Value-type elements are initialized to zero.

This method is an O(n) operation, where n is length.

Example

The following example shows how to create and initialize a one-dimensional Array.

C# Example

using System;

public class ArrayCreateInstanceExample
{

   public static void Main()
   {

      Array intAry = Array.CreateInstance(typeof(int),5);
      for (int i=intAry.GetLowerBound(0);i<=intAry.GetUpperBound(0);i++)
         intAry.SetValue(i*3,i);
      Console.Write("The values of the array are:");
      foreach (int i in intAry)
         Console.Write("{0} ",i);
   
   }

}
   

The output is

The values of the array are: 0 3 6 9 12

Requirements

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