This article was previously published under Q312389
This article has been archived. It is offered "as is" and will no longer be updated.
This article describes how to use Microsoft Visual Basic 2005 or Microsoft Visual Basic .NET to return a strongly-typed array from the ToArray(type) method. This article applies to Visual Basic 2005 or Visual Basic .NET if you set Option Strict On. If you set Option Strict Off, Visual Basic allows the implicit cast that is described in the article.
The parameter-less ToArray method of the ArrayList class returns an array of type Object. You cannot use the parameter-less implementation of ToArray to cast the Object array to an array of your type. For example, if you add a number of Customer objects to an ArrayList, the underlying list is not made a Customer array. This causes the following statement to fail with the System.InvalidCastException exception.
Dim custArray() As customer = CType(myArrayList.ToArray(), customer())
To return a strongly-typed array, use the overloaded ToArray method that accepts an object type as a parameter. For example, the following statement succeeds.
Dim custArray() As customer = CType(al.ToArray(GetType(customer)), customer())
Important All elements of the ArrayList must be of the same object type. The ToArray method fails if you attempt to cast an ArrayList of heterogeneous objects to a specific type.
Start a new Console Application project by using Visual Basic 2005 or Visual Basic .NET. By default, a file that is named Module1.vb is created.
Replace the code in Module1.vb with the following code.
Option Strict OnModule Module1 Sub Main() Dim tempCust As customer Dim c As New customer() c.cname = "anonymous" Dim al As New ArrayList() al.Add(c) Dim cArray As Object() = al.ToArray() 'Display the type of the ArrayList. Console.WriteLine(cArray.GetType) 'Uncomment the next line to reproduce the InvalidCastException. 'Dim custArray() As customer = CType(al.ToArray(), customer()) 'Comment the next line to reproduce the InvalidCastException. Dim custArray() As customer = CType(al.ToArray(GetType(customer)), customer()) Console.WriteLine(custArray.GetType) End Sub Public Class customer Public cname As String End ClassEnd Module
Press CTRL+F5 to build and then run the project. (CTRL+F5 allows the Console window to remain open.)
To reproduce the InvalidCastException exception, follow the two commenting instructions in the sample code.