Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert boxed ienumerable into object array without knowing explicit type

Tags:

c#

I've got a little code that pulls a boxed ienumerable instance out of an expression tree. The code needs to convert it into object[].

So far I've gotten away with assuming it'll be IEnumerable<string> and thus casting it followed with .ToArray().

Circumstances have changed and now it could also possibly be a IEnumerable<int>. I still need to change the box into an object[] and don't really care what the type is.


object list = Expression.Lambda(methodCallExpression.Object).Compile().DynamicInvoke();

var enumerable = (IEnumerable<string>)list;
object[] values = enumerable.ToArray();

UPDATE:

Strings are references and Integers are value types. I've found that while I can box the reference to an array of ints, I cannot pretend it's an array of boxed ints as int's cannot be boxed.

An exception of type 'System.InvalidCastException' occurred in System.Core.dll but was not handled in user code Additional information: Unable to cast object of type 'System.Collections.Generic.List1[System.Int32]' to type 'System.Collections.Generic.IEnumerable1[System.Object]'.

object list = Expression.Lambda(methodCallExpression.Object).Compile().DynamicInvoke(); 
var enumerable = (IEnumerable<object>)list; 
object[] values = enumerable.ToArray();
like image 709
Daniel Revell Avatar asked Oct 22 '25 15:10

Daniel Revell


1 Answers

Just call Cast before ToArray:

object[] values = enumerable.Cast<object>().ToArray();

Note that this casts each item, not the entire collection. You can't "cast" a collection of ints to a collection of objects, you have to convert each item to an object (i.e. box them).

like image 83
D Stanley Avatar answered Oct 24 '25 04:10

D Stanley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!