Search code examples
c#nreco

How to parse a string expression with bitwise operators using Nreco LambdaParser package?


I have the following code but it doesn't compile, I tried to find anything about bitwise operators when using Nreco lambda parser package but I havent found a example.

    var lambdaParser = new NReco.Linq.LambdaParser();
    var varContext = new Dictionary<string, object>();

    varContext["numA"] = 3;

    var varResult = lambdaParser.Eval("(numA & 1) == 1 ? true : false", varContext);
    Console.WriteLine(varResult);

Solution

  • NReco.LambdaParser doesn't support bitwise AND/OR operations (both "&&" / "and" means boolean AND). However you can add to varContext your helper function for your purpose:

    varContext["BitAnd"] = (Func<int, int, int>)((a, b) => v & b);
    var varResult = lambdaParser.Eval("BitAnd(numA, 1) == 1 ? true : false", varContext);
    

    or even

    varContext["CheckBit"] = (Func<int, int, bool>)((a, b) => (v & b) == b);
    var varResult = lambdaParser.Eval("CheckBit(numA, 1) ? true : false", varContext);
    

    This approach allows you to extend LambdaParser for functions you need in your expressions.