ncalc

Can NCalc be configured to evaluate a bool to 0 or 1?


I just got caught by surprise because management thinks it's a good idea to use Boolean expressions in calculations such as

x = (y < 4) * 1 + (z < 8) * 4 ...

I use NCalc for formula evaluation, unfortunately NCalc complains because I'm trying to multiply an integer and a bool.

Is there a way to expand NCalc so false is converted to 0 and true is converted to 1 or will I have to dig deep and make some modifications to the NCalc codebase?


Solution

  • I ended up changing the source code. Just in case anybody should run into the same issue, there's a bunch of switch statements in Numbers.cs where you can change the behavior for every type of operator. In my particular case that was Multiply(object a, object b) where I changed the default behavior from throwing an exception to this:

    case TypeCode.Int32:
       switch (typeCodeB)
       {
          case TypeCode.Boolean: return ((bool) b) ? (Int32)a : 0;
       }
    ...