Converting an array of type T to an array of type I where T implements I in C#

arrays, c#, ienumerable, list

Solution

The issue here is that C# doesn't support co-variance (at least not until C# 4.0, I think) in generics so implicit conversions of generic types won't work.

You could try this:

List<I> list = new List<I>();
foreach (T[] arrayOfA in arrays)
{
    list.AddRange(Array.ConvertAll<T, I>(arrayOfA, t => (I)t));
}
return list.ToArray();

For anyone that strumbles across this question and is using .NET 3.5, this is a slightly more compact way of doing the same thing, using Linq.

List<I> list = new List<I>();
foreach (T[] arrayOfA in arrays)
{
    list.AddRange(arrayOfA.Cast<I>());
}
return list.ToArray();

Problem

I am trying to accomplish something in C# that I do easily in Java. But having some trouble. I have an undefined number of arrays of objects of type T. A implements an interface I. I need an array of I at the end that is the sum of all values from all the arrays. Assume no arrays will contain the same values. This Java code works. ``` ArrayList<I> list = new ArrayList<I>(); for (Iterator<T[]> iterator = arrays.iterator(); iterator.hasNext();) { T[] arrayOfA = iterator.next(); //Works like a charm list.addAll(Arrays.asList(arrayOfA)); } return list.toArray(new T[list.size()]); ``` However this C# code doesn't: ``` List<I> list = new List<I>(); foreach (T[] arrayOfA in arrays) { //Problem with this list.AddRange(new List<T>(arrayOfA)); //Also doesn't work list.AddRange(new List<I>(arrayOfA)); } return list.ToArray(); ``` So it's obvious I need to somehow get the array of `T[]` into an `IEnumerable<I>` to add to the list but I'm not sure the best way to do this? Any suggestions? EDIT: Developing in VS 2008 but needs to compile for .NET 2.0.

Original source