I am doing some parsing from user input, and here I need to parse array of arguments that should be of certain Type.
At the moment of parsing I do not know of which Type each argument shoud be, but it could be evaluated to any Type. So, i decided to temporarily store them in an array of objects. But when i try to do something like this:
NewArrayExpression returnValue = Expression.NewArrayInit(typeof(object), expressionList);
I get following exception: An expression of type 'System.Int32' cannot be used to initialize an array of type 'System.Object'.
That is, I suppose, because no implicit boxing is happening. So i box it myself:
expressionList.Add(Expression.TypeAs(expression, typeof(object))); or
expressionList.Add(Expression.Convert(expression, typeof(object)));
So far so good: I got list of objects of various types in an array.
But, when i finally get the desired Type, I try converting all of the values from upper array to that Type (lets say that type being usualy an int) I convert it:
Expression.Convert(expr, typeof(int)); or
Expression.Unbox(expr, typeof(int));
This is debug view of both commands when expr is actualy an string "aaaaa":
(System.Int32)((System.Object)"aaaaa")
Now, here lies my problem: This WILL NOT throw an exception. But it will when expression is finally compiled. I mean, string is not an int.
Maybe this really shouldn't throw an exception, I don't know. But this doesn't work for me.
Is there a cure for this?
EDIT: The code looks like this:
static Expression InArguments(ParameterExpression pe, string[] arguments)
{
List<Expression> listaExpr = new List<Expression>();
foreach (string s in arguments)
{
Expression expression = Complete(pe, s); // evaluate argument
// listaExpr.Add(Expression.Convert(expression, typeof(object)));
}
return Expression.NewArrayInit(typeof(object), listaExpr);
}