Convert ArrayList to Array
This page was last reviewed on 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.
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.
typeof, nameof
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.
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.
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Oct 26, 2023 (edit).
© 2007-2024 Sam Allen.