how to handle null in IF expression of NCALC

3.1k Views Asked by At

I have a complex NCALC if expression which goes something like this:

if ( {0} == null || {1} == 0 ,{2} * ({3} * {4} + {5}), ({2} * ({3} * {4} + {5}))/{1})

This gives me some unexpected error such as below:

missing ')' at '==' at line 1:6

missing EOF at 'UnsetValue' at line 1:37

What the issue here- i couldnt find if NCALC supports null. if it does, then what could be wrong in the above expression. Kindly help!!

2

There are 2 best solutions below

1
On BEST ANSWER

My experience has been ncalc does not support null. But you can write your own function to evaluate if the parameter passed in has a value and return a true / false.

To do this, wire up an EvaluateFunction. (small example below)

var exp = new NCalc.Expression("if(HASVALUE([variable], [variable] *2, 0)")
exp.Parameters["variable"] = 2;
exp.EvaluateFunction += SpecRule_EvaluateFunction;

private void SpecRule_EvaluateFunction(string name, NCalc.FunctionArgs args)
{
   switch (name.ToUpper())
   {
       case "HASVALUE":
          if (args.Parameters.Length < 1)
               throw new ArgumentException("IsNull must have at least 1 argument");
    
             args.Result = args.Parameters[0].Parameters.Values.FirstOrDefault() != null;
    
             break;
    }
}
0
On

Atleast now in 2021, there're options you can pass to NCalc to allow null values.

Expression e = new Expression(expression, EvaluateOptions.AllowNullParameter);