Convert Object Array to another type array using Reflection

0 votes
asked Dec 2, 2010 by shake

I have an object array and I want to convert it to a specific type array. I have the type to convert it into which I get at run time. But I am having a problem doing the actual conversion.

If I use the Convert.ChangeType, I get the error that Object must implement IConvertible

The Array.ConvertAll is template based and requires that I pass the destination type as a template which I only know at run time. I even tried to do use reflection to call this method but I cannot pass the lambda expression as an argument to the MethodInfo.Invoke method.

Any Ideas?

Right I have the following which is not working:

Type convertTo = GetFinalType();
Object[] objArr = GetObjectArray();
var arr = Array.ConvertAll(objArr,elem=> Convert.ChangeType(elem,convertTo));

5 Answers

0 votes
answered Jan 2, 2010 by mark-avenius

You are close; does the following work, or was objType a typo?

Type convertTo = GetFinalType();
Object[] objArr = GetObjectArray();
var arr = Array.ConvertAll(objArr,elem=> Convert.ChangeType(elem, convertTo));
0 votes
answered Jan 2, 2010 by cdhowie

The code is failing because some object in your array is not a primitive type, or is not something that implements the IConvertible interface You cannot use Convert.ChangeType() on such objects.

0 votes
answered Jan 2, 2010 by shake

I did it the worst way possible but I managed it somehow. I created a new class

public class Tools
    public static T[] Convert<T>(object[] objArr)
        IList<T> list = new List<T>();

        foreach (var o in objArr)

        return list.ToArray();

And where I needed the conversion, I used:

MethodInfo method = typeof(Tools).GetMethod("Convert");
MethodInfo generic = method.MakeGenericMethod(new Type[] { t });

object o = generic.Invoke(null, new object[] { objArr });

var m =  Convert.ChangeType(o,typeof(tArr));


t = typeof(MyClass); 
tArr = typeof(MyClass[]);
0 votes
answered Jan 31, 2011 by doug

Have you tried this?

var finalType = GetFinalType();
var objArr = GetObjectArray();
var arr = Array.CreateInstance(finalType, objArr.Length);
Array.Copy(objArr, arr, objArr.Length);

That's untested, but it should work. It's more compact and doesn't (really) use reflection.

0 votes
answered Sep 15, 2017 by bryun

This is a solution that worked for me:

public static T[] CastArrayToType<T>(object[] collection)
    return Array.ConvertAll<object, T>(
        delegate(object prop)
            return (T)prop;
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter