How can I dynamically perform a comparison from a string?

If I had a line with something like this:

"if (24 == 24) AND ((true == false) OR (true == true)) AND ('HELLO' != 'WORLD')" 

How can I dynamically evaluate this in code using C # /. Net?

We have a dynamic "rule engine" where the user defines the rules. So the rule could be

 if (@Number == 24) AND ((@SomeVal1 == false) OR (@SomeVal2 == true)) AND ('@CustomerFirstName' != '@CustomerLastName'). 

We would like to do a simple search / replace for @ variables and then evaluate the string.

+4
source share
5 answers

Data processing, since the code always carries some significant risks, so please carefully think about what security consequences it will take for your application.

C # is usually not a dynamic language, but you can hack this functionality. Here is an example of a C # eval version.

Depending on the need, expression trees can also be an option, as @Femaref points out.

+2
source

You can, but it will take many jumps through the hoops. However, the .net structure has Expression Trees that can be used to create such expressions and compile them into lambda.

+2
source

Besides Femaref's answer, you can also try to interpret the string yourself.

Thus, it will be a kind of DSL (domain language). Here you can learn more about DSL:

ANTLR (a useful tool for creating DSL) http://www.antlr.org/wiki/display/ANTLR3/Antlr+3+CSharp+Target

+1
source

I am afraid there is no easy way to do this. You can either parse your string manually, and then use Reflection to get the variables or fields or properties referenced by your @foo syntax, or you can create a dynamic type using a method that reflects your rule.

0
source

I'm not sure how complex expressions you can have. But here is a good library that, I think, could handle the expression of your example. http://ncalc.codeplex.com/

0
source

All Articles