ToArray Method (Type)
Collapse the table of content
Expand the table of content

ArrayList.ToArray Method (Type)

 

Copies the elements of the ArrayList to a new array of the specified element type.

Namespace:   System.Collections
Assembly:  mscorlib (in mscorlib.dll)

public virtual Array ToArray(
	Type type
)

Parameters

type
Type: System.Type

The element Type of the destination array to create and copy elements to.

Return Value

Type: System.Array

An array of the specified element type containing copies of the elements of the ArrayList.

Exception Condition
ArgumentNullException

type is null.

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 System;
using System.Collections;

public class SamplesArrayList  {

   public static void Main()  {

      // Creates and initializes a new ArrayList.
      ArrayList myAL = new 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.
      String[] myArr = (String[]) myAL.ToArray( typeof( string ) );

      // Displays the contents of the string array.
      Console.WriteLine( "The string array contains the following values:" );
      PrintIndexAndValues( myArr );

   }

   public static void PrintIndexAndValues( ArrayList myList )  {
      int i = 0;
      foreach ( Object o in myList )
         Console.WriteLine( "\t[{0}]:\t{1}", i++, o );
      Console.WriteLine();
   }

   public static void PrintIndexAndValues( 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

*/

Universal Windows Platform
Available since 10
.NET Framework
Available since 1.1
Return to top
Show:
© 2016 Microsoft