ncalc

how to handle null in IF expression of NCALC


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!!


Solution

  • 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;
        }
    }