Home
C#
Convert ArrayList to Array
Updated Oct 26, 2023
Dot Net Perls
Convert ArrayList, array. An 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.
Convert ArrayList, List
ToArray details. ToArray is found on the ArrayList type. It is not an extension method—it is part of the ArrayList class itself.
ArrayList
Example. 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.
Type
typeof
Note The string keyword is used, and not a string literal. Specifying types with "String Names" is less clear.
Note 2 The code populates a new ArrayList with 4 object instances containing string data (string literals).
Note 3 The 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.
as
null
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
Internals. 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.
Array.Copy
Tip This provides superior performance over manually copying elements in your C# program.
Summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Oct 26, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen