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