ArrayList
, arrayAn ArrayList
has similarities to an array. It stores a 1-dimensional collection of elements. It can be converted to an array with the ToArray
method.
ToArray
detailsToArray
is found on the ArrayList
type. It is not an extension method—it is part of the ArrayList
class
itself.
You will need to provide a Type parameter to the ToArray
method on ArrayList
. This tells the method the target type. Here we do that with the typeof
operator.
string
keyword is used, and not a string
literal. Specifying types with "String
Names" is less clear.ArrayList
with 4 object instances containing string
data (string
literals).as
-cast is necessary to use strong typing on the result from ToArray
. It will result in a null
value if the cast does not succeed.using System; using System.Collections; // Create an ArrayList with 4 strings. ArrayList list = new ArrayList(); list.Add("flora"); list.Add("fauna"); list.Add("mineral"); list.Add("plant"); // Convert ArrayList to array. string[] array = list.ToArray(typeof(string)) as string[]; // Loop over array. foreach (string value in array) { Console.WriteLine(value); }flora fauna mineral plant
When we open up the ToArray
instance method in IL Disassembler, we see that this method calls into the Array.Copy
method. Array.Copy
uses an external, native-code implementation.
We used the ArrayList
's ToArray
method to convert the contents of an ArrayList
to a string
array. The example here can be adapted to other reference and value types.