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.List
1[System.Int32]' to type 'System.Collections.Generic.IEnumerable
1[System.Object]'.
object list = Expression.Lambda(methodCallExpression.Object).Compile().DynamicInvoke();
var enumerable = (IEnumerable<object>)list;
object[] values = enumerable.ToArray();