How to convert object[] to a more specifically typed array

Viewed 10840

This would be pretty straight forward if I knew the types at compile time or if it was a generic parameter, because I could do something like myArray.Cast<T>() But what I actually have is essentially this. I do not have a known type or generic parameter. I have a System.Type variable.

// could actually be anything else
Type myType = typeof(string);  

// i already know all the elements are the correct types
object[] myArray = new object[] { "foo", "bar" }; 

Is there some kind of reflection magic I can do to get a string[] reference containing the same data? (where string isn't known at compile time)

6 Answers

This is not a one liner but it can be done with two lines. Given your specified Array of elements of the correct type myArray and the specified Type parameter myType, dynamically calling .Cast<"myType">.ToArray() would work.

var typeConvertedEnumerable = typeof(System.Linq.Enumerable)
    .GetMethod("Cast", BindingFlags.Static | BindingFlags.Public)
    .MakeGenericMethod(new Type[] { myType })
    .Invoke(null, new object[] { myArray });
var typeConvertedArray = typeof(System.Linq.Enumerable)
    .GetMethod("ToArray", BindingFlags.Static | BindingFlags.Public)
    .MakeGenericMethod(new Type[] { myType })
    .Invoke(null, new object[] { typeConvertedEnumerable });

While the method generation is slower than a direct call, it is O(1) on the size of the array. The benefit of this approach is, if IEnumerable<"myType"> would be acceptable, the second line is not needed, and therefore I do not believe the array will be copied.

Related