Array::CreateInstance Method (Type, Int32)
Namespace: System
Assembly: mscorlib (in mscorlib.dll)
Parameters
- elementType
- Type: System::Type
The Type of the Array to create.
- length
- Type: System::Int32
The size of the Array to create.
Return Value
Type: System::ArrayA new one-dimensional Array of the specified Type with the specified length, using zero-based indexing.
| Exception | Condition |
|---|---|
| ArgumentNullException | elementType is nullptr. |
| ArgumentException | elementType is not a valid Type. |
| NotSupportedException | elementType is not supported. For example, Void is not supported. -or- elementType is an open generic type. |
| ArgumentOutOfRangeException | length is less than zero. |
Unlike most classes, Array provides the CreateInstance method, instead of public constructors, to allow for late bound access.
Reference-type elements are initialized to nullptr. Value-type elements are initialized to zero.
This method is an O(n) operation, where n is length.
The following code example shows how to create and initialize a one-dimensional Array.
using namespace System; void PrintValues( Array^ myArr ); void main() { // Creates and initializes a one-dimensional Array instance of type Int32. Array^ my1DArray = Array::CreateInstance( Int32::typeid, 5 ); for ( int i = my1DArray->GetLowerBound( 0 ); i <= my1DArray->GetUpperBound( 0 ); i++ ) my1DArray->SetValue( i + 1, i ); // Displays the values of the Array. Console::WriteLine( "The one-dimensional Array instance contains the following values:" ); PrintValues( my1DArray ); } void PrintValues( Array^ myArr ) { System::Collections::IEnumerator^ myEnumerator = myArr->GetEnumerator(); int i = 0; int cols = myArr->GetLength( myArr->Rank - 1 ); while ( myEnumerator->MoveNext() ) { if ( i < cols ) { i++; } else { Console::WriteLine(); i = 1; } Console::Write( "\t{0}", myEnumerator->Current ); } Console::WriteLine(); } /* This code produces the following output. The one-dimensional Array instance contains the following values: 1 2 3 4 5 */
Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.