sklose/NCalc2

Cannot evaluate formula

Closed this issue · 2 comments

Rbn3D commented

Consider the following code:

public static InputValidation ValidCustomFormula = delegate (string val) {
            if (String.IsNullOrWhiteSpace(val))
                return "";
            else
            {

                var expr = new Expression(val);

                decimal x = 5m;
                decimal a = 6m;
                decimal b = 7m;

                expr.Parameters["x"] = x;
                expr.Parameters["a"] = a;
                expr.Parameters["b"] = b;

                try
                {
                    Func<float> f = expr.ToLambda<float>(); // Here it throws System.ArgumentNullException. Parameter name: expression

                    float res = f();
                }
                catch(Exception e)
                {
                    return "There was an error while parsing the custom formula: " + e.Message;
                }
          }
    }

    var res = ValidCustomFormula("2 + 2 - a - b - x");

As long as I don't include any parameter in the expression itselt (i.e.: "2 + 2 + 2") it works, but it doesn't when I include some parameter. Am I missing something? Looks like a bug.

Thanks.

Thanks for reporting this issue. The Parameters dictionary was not supported by the lambda expression compiler. I added support for that, but notice that values contained in the Parameters dictionary become constants in the lambda expression. If you need the ability to change those values after compilation you should look into using an ExpressionContext as described in README.md.

Rbn3D commented

Wow, thanks for the quick fix and response, I'll check it out 👍