Convert an ArrayList to an Array

Problem

You need to convert an ArrayList into a strongly typed array.

Solution

Use the ArrayList.ToArray method.

Discussion

Converting an ArrayList to an ordinary array is a useful task. For example, you might create a utility function that uses an ArrayList internally to quickly create a collection and dynamically add items. Using an ArrayList is intrinsically easier than using an array, because you don’t need to worry about array dimensions. However, when you return the information from the function, you should use a generic array, which is more common and has the advantage of type safety.

In theory, you could inspect the Count property of the ArrayList, create a corresponding array, and iterate through the ArrayList ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.