TheDeveloperBlog.com


C# Convert ArrayList to Array

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

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

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

The code defines the Main entry point and then populates a new ArrayList with four object instances containing string data (string literals). In this example, the strings are interned by the runtime, so share memory.

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. In some programs, it is best to check for null.

AsNull

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