Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you do dynamic script evaluation in C#?

What is the state of dynamic code evaluation in C#? For a very advanced feature of an app I'm working on, I'd like the users to be able to enter a line of C# code that should evaluate to a boolean.

Something like:

DateTime.Now.Hours > 12 && DateTime.Now.Hours < 14

I want to dynamically eval this string and capture the result as a boolean.

I tried Microsoft.JScript.Eval.JScriptEvaluate, and this worked, but it's technically deprecated and it only works with Javascript (not ideal, but workable). Additionally, I'd like to be able to push objects into the script engine so that they can be used in the evaluation.

Some resources I find mentioned dynamically compiling assemblies, but this is more overhead than I think I want to deal with.

So, what is the state of dynamic script evaluation in C#? Is it possible, or am I out of luck?

like image 515
Deane Avatar asked Jun 16 '10 01:06

Deane


2 Answers

You use the DLR's ScriptEngine, here is an example:

http://www.codeproject.com/KB/codegen/ScriptEngine.aspx

like image 183
MatthewMartin Avatar answered Nov 09 '22 16:11

MatthewMartin


The most informative link is this one:

Execute a string in C# 4.0

Expression Trees might also be of interest:

http://community.bartdesmet.net/blogs/bart/archive/2009/08/10/expression-trees-take-two-introducing-system-linq-expressions-v4-0.aspx

Alternatively these links:

  • http://www.codeproject.com/KB/dotnet/Expr.aspx
  • How can I evaluate a C# expression dynamically?
  • How can I evaluate C# code dynamically?
like image 33
Matt Mitchell Avatar answered Nov 09 '22 14:11

Matt Mitchell