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.
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.
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 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).