How to return a strongly typed array from the ToArray method by using Visual C#

For a Microsoft Visual Basic .NET version of this article, see 312389 .



This step-by-step article shows you how to use Visual C# to return a strongly typed array from the ToArray(type) method.

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:
Customer [] customer = (Customer[])myArrayList.ToArray();

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:

Customer [] customer = (Customer[])myArrayList.ToArray(typeof(Customer));
NOTE: C# disallows an implicit cast, so you must explicitly cast the result of the ToArray method.

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

  1. Start a new Console Application project in Visual C# .NET or in Microsoft Visual C# 2005.
  2. Replace the code in Class1.cs with the following code.

    Note In Visual Studio 2005, the default file is Program.cs.
    using System;
    using System.Collections;

    class Class1

    static void Main(string[] args)

    customer c = new customer();
    c.cname = "anonymous";

    ArrayList al=new ArrayList();
    object[] cArray = al.ToArray();
    //Display the type of the ArrayList.

    //Uncomment the next line to reproduce the InvalidCastException.
    //customer[] custArray = (customer[])(al.ToArray());

    //Comment the next line to reproduce the InvalidCastException.
    customer[] custArray = (customer[])al.ToArray(typeof(customer));


    class customer
    public string cname;

  3. Press the CTRL+F5 key combination to build and run the project. (CTRL+F5 allows the Console window to remain open.)
  4. To reproduce the InvalidCastException exception, follow the two commenting instructions in the sample code.

ID do Artigo: 312390 - Última Revisão: 11 de jul de 2008 - Revisão: 1