2

I have a string with conditions like this:

string conditions = "true && true || false || true ";

How do I assert that the entire string is either true or false?

For example, something like this:

if( Assert(conditions) == true ){
    // passed
}

I need something that is readily available in C# without resorting to a 3rd party library.

Bill Software Engineer
  • 7,362
  • 23
  • 91
  • 174

2 Answers2

1

Parse the string with a trivial tokeniser unless you know you'll have bracketized operations (in which case use a finite state automaton parser) - this will convert the string into an object representation, then use the shunting-yard algorithm to evaluate the string.

The grammar as exemplified in your question seems simplistic, and adopting equal-precedence operators without brackets will severely restrict the kinds of expressions possible.

Dai
  • 141,631
  • 28
  • 261
  • 374
1

This is a static method that will do what you want, but it's SLOOOW!!

public static object Eval(string booleanExpression) {

  var c = new Microsoft.CSharp.CSharpCodeProvider();
  var icc = c.CreateCompiler();
  var cp = new System.CodeDom.Compiler.CompilerParameters();

  cp.CompilerOptions = "/t:library";
  cp.GenerateInMemory = true;

  StringBuilder sb = new StringBuilder("");
  sb.Append("using System;\n" );

  sb.Append("namespace BooleanEvaluator{ \n");
  sb.Append("public class BooleanEvaluator{ \n");
  sb.Append("public bool Evaluate(){\n");
  sb.Append("return "+booleanExpression+"; \n");
  sb.Append("} \n");
  sb.Append("} \n");
  sb.Append("}\n");

  var cr = icc.CompileAssemblyFromSource(cp, sb.ToString());

  System.Reflection.Assembly a = cr.CompiledAssembly;
  object o = a.CreateInstance("BooleanEvaluator.BooleanEvaluator");

  Type t = o.GetType();
  MethodInfo mi = t.GetMethod("Evaluate");

  return (bool) mi.Invoke(o, null);
}

However, the tokenizer and parser that Dai suggests can be easily generated with ANTLR and a boolean expression grammar. That will be much faster! See: ANTLR v3 grammar for boolean/conditional expression

Community
  • 1
  • 1
Diego
  • 18,035
  • 5
  • 62
  • 66
  • Excellent, this will do. I can't add any 3rd party software, and I don't expect the expression to be longer than maybe maxim of 10 statements, so it's fine. Thanks a lot. – Bill Software Engineer Feb 16 '16 at 17:57