This documentation is archived and is not being maintained.
ArrayList::ToArray Method (Type)
Visual Studio 2010
Copies the elements of the ArrayList to a new array of the specified element type.
Assembly: mscorlib (in mscorlib.dll)
Parameters
- type
- Type: System::Type
The element Type of the destination array to create and copy elements to.
Return Value
Type: System::ArrayAn array of the specified element type containing copies of the elements of the ArrayList.
| Exception | Condition |
|---|---|
| ArgumentNullException | type is nullptr. |
| InvalidCastException | The type of the source ArrayList cannot be cast automatically to the specified type. |
All of the objects in the ArrayList object will be cast to the Type specified in the type parameter.
The elements are copied using Array::Copy, which is an O(n) operation, where n is Count.
The following copy example shows how to copy the elements of an ArrayList to a string array.
using namespace System; using namespace System::Collections; void PrintIndexAndValues( ArrayList^ myList ); void PrintIndexAndValues( array<String^>^myArr ); int main() { // Creates and initializes a new ArrayList. ArrayList^ myAL = gcnew ArrayList; myAL->Add( "The" ); myAL->Add( "quick" ); myAL->Add( "brown" ); myAL->Add( "fox" ); myAL->Add( "jumped" ); myAL->Add( "over" ); myAL->Add( "the" ); myAL->Add( "lazy" ); myAL->Add( "dog" ); // Displays the values of the ArrayList. Console::WriteLine( "The ArrayList contains the following values:" ); PrintIndexAndValues( myAL ); // Copies the elements of the ArrayList to a string array. array<String^>^myArr = reinterpret_cast<array<String^>^>(myAL->ToArray( String::typeid )); // Displays the contents of the string array. Console::WriteLine( "The string array contains the following values:" ); PrintIndexAndValues( myArr ); } void PrintIndexAndValues( ArrayList^ myList ) { int i = 0; IEnumerator^ myEnum = myList->GetEnumerator(); while ( myEnum->MoveNext() ) { Object^ o = safe_cast<Object^>(myEnum->Current); Console::WriteLine( "\t[{0}]:\t{1}", i++, o ); } Console::WriteLine(); } void PrintIndexAndValues( array<String^>^myArr ) { for ( int i = 0; i < myArr->Length; i++ ) Console::WriteLine( "\t[{0}]:\t{1}", i, myArr[ i ] ); Console::WriteLine(); } /* This code produces the following output. The ArrayList contains the following values: [0]: The [1]: quick [2]: brown [3]: fox [4]: jumped [5]: over [6]: the [7]: lazy [8]: dog The string array contains the following values: [0]: The [1]: quick [2]: brown [3]: fox [4]: jumped [5]: over [6]: the [7]: lazy [8]: dog */
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.
Show: