Home
VB.NET
Convert ArrayList to Array
Updated Sep 24, 2022
Dot Net Perls
Convert ArrayList, Array. In VB.NET an ArrayList can be converted to an array. This is possible with the ToArray Function. With it we get an Object array from an ArrayList.
Function info. ToArray is useful—it is not the same as the ToArray extension from System.Linq. We can perform the conversion with just one line of code.
To start, we create an ArrayList. All the elements in the ArrayList are of type String. This is important—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.
Object Array
Note We can not directly cast the array to a String(). This exception is reported.
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
Dot Net Perls
Unhandled Exception: System.InvalidCastException: Unable to cast object of type 'System.Object[]' to type 'System.String[]'.
Discussion. The ArrayList makes converting your collection to an array more difficult. If you use the List type, you can convert to a typed array such as String(). This results in clearer code.
List
Summary. We used the ToArray function on the ArrayList type to convert an ArrayList to an Object() array. We looked at the exception that is thrown when you try to cast the result array.
ArrayList
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 Sep 24, 2022 (edit).
Home
Changes
© 2007-2025 Sam Allen