Is this a bug in ArrayList.ToArray() ?

I think I may have found a bug in System.Collections.ArrayList.ToArray(). The following code throws a System.InvalidCastException with the following message:
“At least one element in the source array could not be cast down to the destination array type.”



using System;
using System.Collections;

namespace InterfaceToArrayTest
{
  public interface Parent
  {
    string ParentProperty { get; }
  }

  public interface Child: Parent
  {
    string ChildProperty { get; }
  }

  public class Implements: Child
  {
    #region Child Members

    public string ChildProperty
    {
      get
      {
        return "child";
      }
    }

    #endregion

    #region Parent Members

    public string ParentProperty
    {
      get
      {
        return "parent";
      }
    }

    #endregion
  }

  class ArrayListToArrayTest
  {
    [STAThread]
    static void Main(string[] args)
    {
      ArrayList list = new ArrayList();

      for (int x = 0; x < 10; x++)
      {
        list.Add(new Implements());
      }

      Child[] children = (Child[]) list.ToArray(typeof(Child[]));
    }
  }
}

6 Responses to “Is this a bug in ArrayList.ToArray() ?”

  1. Lee Falin says:

    Change the last line to this:

    Child[] children = (Child[]) list.ToArray(typeof(Child));

  2. Lee Falin says:

    Let me explain that further.

    If you look at the ToArray implementation in reflector:

    public virtual Array ToArray(Type type)
    {
    if (type == null)
    {
    throw new ArgumentNullException(“type”);
    }
    Array array1 = Array.CreateInstance(type, this._size);
    Array.Copy(this._items, 0, array1, 0, this._size);
    return array1;
    }

    You see that an array is created of the type you specify. In your code sample, you are telling it to create an array of type Child[], in other words an array of Child arrays. What you really want is an array of Childs (or children)

  3. vaderpi says:

    Ah. I feel like an idiot now. Hehe. I wasted at least a half an hour on this, too. :)

  4. [...] ically dead Ha! I am not crazy! While the example program that I posted a few weeks ago had a typo in it, it did not fully reproduce the problem I was experiencing. [...]

  5. van says:

    what if the same exception is thrown even if we use

    Child[] children = (Child[]) list.ToArray(typeof(Child));

    I am experiencing this problem. Does anyone have solution ??

  6. vaderpi says:

    If the Child objects are remoting proxies, then you will get this problem.

Leave a Reply