Article ID: 312389 - View products that this article applies to.
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.
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.
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.
Article ID: 312389 - Last Review: February 28, 2014 - Revision: 3.3
Contact us for more help
Connect with Answer Desk for expert help.