HomeSearch

C# Convert ArrayList to Array (Use ToArray)

Convert an ArrayList to an array with typeof and the ToArray method.
Convert ArrayList, array. An ArrayList has similarities to an array. It stores a one-dimensional collection of elements. It can be converted to an array with the ToArray method. ToArray is found on the ArrayList type.ArrayList
Example. You will need to provide a Type parameter to the ToArray method on ArrayList. This is because otherwise the method would not know what type to convert each element to. Here we do that with the typeof operator.TypeTypeof, nameof

Note: The string keyword is used, and not a string literal. Specifying types with "String Names" is less clear.

Main: The code populates a new ArrayList with 4 object instances containing string data (string literals).

Cast: 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.

AsNull
C# program that converts an ArrayList using System; using System.Collections; class Program { static void Main() { // // 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); } } } Output flora fauna mineral plant
Internals. When we open up the ToArray instance method in IL Disassembler, we see that this method (along with the CopyTo 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. We also looked inside the base class library.Convert ArrayList to List
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls