VB.NET Convert ArrayList to Array

Conversion or change

You want to convert your ArrayList collection to an array in your VB.NET program. With the ToArray Function, you can get an Object array from an ArrayList. ToArray is useful.

Example

Note

To start, we create an ArrayList and populate it with three String references. Please notice how all the elements in the ArrayList are of type String. This is important because when we call ToArray, we get an Object array, not a String array. However, when we loop through the Object array, we can cast each element to a String.

String Notes Object Array

This VB program converts an ArrayList to an array. It uses the ToArray Function.

Program that converts ArrayList to Object array [VB.NET]

Module Module1
    Sub Main()
	' Create ArrayList.
	Dim list As ArrayList = New ArrayList()
	list.Add("Dot")
	list.Add("Net")
	list.Add("Perls")

	' Get array of objects.
	Dim array() As Object = list.ToArray()

	For Each element In array
	    ' Cast object to string.
	    Dim value As String = element
	    Console.WriteLine(value)
	Next
    End Sub
End Module

Output

Dot
Net
Perls

Note: It is not possible to cast the array to a String() directly. This exception is reported:

Unhandled Exception: System.InvalidCastException: Unable to cast object of type 'System.Object[]' to type 'System.String[]'.

ArrayList versus List

List type.

The ArrayList makes converting your collection to an array more difficult than it needs to be. If you use the List type, you can convert to a typed array such as String(). This results in much clearer code. I recommend the List type in almost all programs.

List Tips

Summary

The VB.NET programming language

We saw how you can use the ToArray function on the ArrayList type to convert your ArrayList to an Object() array. We looked at the exception that is thrown when you try to cast the result array, and also pointed out the superior List type.

ArrayList Examples VB.NET Tutorials
.NET