Microsoft KB Archive/312389

= How to return a strongly-typed array from the ToArray(type) method by using Visual Basic 2005 or Visual Basic .NET =

Article ID: 312389

Article Last Modified on 12/6/2006

-

APPLIES TO


 * Microsoft Visual Basic 2005
 * Microsoft Visual Basic .NET 2003 Standard Edition
 * Microsoft Visual Basic .NET 2002 Standard Edition

-



This article was previously published under Q312389



SUMMARY
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.

Step-by-step example
 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 On

Module Module1

Sub Main Dim tempCust As customer Dim c As New customer c.cname = &quot;anonymous&quot;

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 Class

End 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.

Keywords: kbvs2005swept kbvs2005applies kbhowtomaster KB312389

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.