shake shake - 1 year ago 76
C# Question

Convert Object Array to another type array using Reflection

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));

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download