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[]));
}
}
}
Change the last line to this:
Child[] children = (Child[]) list.ToArray(typeof(Child));
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)
Ah. I feel like an idiot now. Hehe. I wasted at least a half an hour on this, too. :)
[...] 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. [...]
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 ??
If the Child objects are remoting proxies, then you will get this problem.