Converting an array of objects to an array of another type using Reflection

I have an array of objects and I want to convert it to a specific array of types. I have a type to convert to which I get at runtime. But I had a problem with the actual conversion.

If I use Convert.ChangeType, I get an error that Object should implement IConvertible

Array.ConvertAll is template-based and requires that I pass the destination type as a template, which I only know at runtime. I even tried using reflection to call this method, but I cannot pass the lambda expression as an argument to MethodInfo.Invoke.

Any ideas?

Correctly I have the following which does not work:

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

Have you tried this?

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

This is untested, but it should work. It is more compact and does not use (really) reflection.

+11
source

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

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

I did it in the worst way, but I succeeded. 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)
        {
            list.Add((T)o);
        }

        return list.ToArray();
    }
}

And where I need 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));

Where

t = typeof(MyClass); 
tArr = typeof(MyClass[]);
+1
source

The code does not work because any object in your array is not a primitive type, or does not implement an interface IConvertible. You cannot use Convert.ChangeType()for such objects.

0
source

This is the solution that worked for me:

public static T[] CastArrayToType<T>(object[] collection)
{
    return Array.ConvertAll<object, T>(
        collection,
        delegate(object prop)
        {
            return (T)prop;
        }
    );
}
0
source

All Articles