This project has moved and is read-only. For the latest updates, please go here.

Expression of type 'System.Single' cannot be used for return type 'System.Object'

Jul 31, 2014 at 4:11 PM
Hello,

I get the following exception when trying to run the below example:
       Expression of type 'System.Single' cannot be used for return type 'System.Object'
code:
      var expression = new CompiledExpression("float.Parse('3.141592654')");
      var result = expression.Eval();
      Console.WriteLine(result);  // displays Pi
I also get:
Expression of type 'System.Guid' cannot be used for return type 'System.Object'

for this code:
        var expression = new CompiledExpression("Guid.NewGuid()");
        expression.RegisterType("Guid", typeof(Guid));
        var result = expression.Eval();
        Console.WriteLine(result);  // displays a new Guid
Can you please provide some direction on what I may be doing wrong?
Jul 31, 2014 at 4:40 PM
So I've been playing around with the code, trying to make it work, and the code below that I modified in CompiledExpression seems to have fixed my issue, but I am not sure if I am missing something else or whether or not this is the correct long term solution:
    public Func<TResult> Compile(bool isCall = false)
    {
        Expression = WrapExpression(BuildTree(), false);
        Expression conversion = System.Linq.Expressions.Expression.Convert(Expression, typeof(TResult));
        return Expression.Lambda<Func<TResult>>(conversion).Compile();
    }
Aug 1, 2014 at 5:14 PM
Yes, that's right. The whole wrapexpression and casting isn't too clean yet. Ideally I want an API that allows you to easily compile to an Action<T> or a Func<T, TResult> without actually having to do all of the above. Having to account for void expressions and object types complicates things. It might also be beneficial to not introduce a conversion if the expression is already of the same type as TResult.


Aug 8, 2014 at 3:52 AM
Thanks for the tip!

This is what I have until something better comes along:
    public Func<TResult> Compile(bool isCall = false)
    {
        Expression = WrapExpression(BuildTree(), false);

        if (!(Expression is TResult))
            Expression = System.Linq.Expressions.Expression.Convert(Expression, typeof(TResult));

        return Expression.Lambda<Func<TResult>>(Expression).Compile();
    }