Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

eval(string) to C# code

Is it possible to evaluate the following in C# at runtime

I have a class that contains 3 properties (Field,Operator,Value)

 rule.Field;
 rule.Operator;
 rule.Value;

this is my rule class...

Now I have a loop

foreach(item in items)
   {
       // here I want to create a dynamic expression to evaluate at runtime
       // something like
       if (item.[rule.field] [rule.operator] [rule.value])
           { do work }
   }

I just don't know the syntax, or if its possible in C#, I know in JS its possible but that's not a compiled language.

Update

Essentially I want a way to eval(stringCode) or a better more supported way.

like image 485
JL. Avatar asked Nov 30 '22 19:11

JL.


1 Answers

No, C# doesn't support anything like this directly.

The closest options are:

  • Create a full valid C# program and dynamically compile it with CSharpCodeProvider.
  • Build an expression tree, compile and execute it
  • Perform the evaluation yourself (this may actually be easiest, depending on your operators etc)
like image 196
Jon Skeet Avatar answered Dec 06 '22 10:12

Jon Skeet