Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I evaluate a C# expression dynamically?

I would like to do the equivalent of:

object result = Eval("1 + 3"); string now    = Eval("System.DateTime.Now().ToString()") as string 

Following Biri s link, I got this snippet (modified to remove obsolete method ICodeCompiler.CreateCompiler():

private object Eval(string sExpression) {     CSharpCodeProvider c = new CSharpCodeProvider();     CompilerParameters cp = new CompilerParameters();      cp.ReferencedAssemblies.Add("system.dll");      cp.CompilerOptions = "/t:library";     cp.GenerateInMemory = true;      StringBuilder sb = new StringBuilder("");     sb.Append("using System;\n");      sb.Append("namespace CSCodeEvaler{ \n");     sb.Append("public class CSCodeEvaler{ \n");     sb.Append("public object EvalCode(){\n");     sb.Append("return " + sExpression + "; \n");     sb.Append("} \n");     sb.Append("} \n");     sb.Append("}\n");      CompilerResults cr = c.CompileAssemblyFromSource(cp, sb.ToString());     if (cr.Errors.Count > 0)     {         throw new InvalidExpressionException(             string.Format("Error ({0}) evaluating: {1}",              cr.Errors[0].ErrorText, sExpression));     }      System.Reflection.Assembly a = cr.CompiledAssembly;     object o = a.CreateInstance("CSCodeEvaler.CSCodeEvaler");      Type t = o.GetType();     MethodInfo mi = t.GetMethod("EvalCode");      object s = mi.Invoke(o, null);     return s;  }   
like image 247
Daren Thomas Avatar asked Sep 10 '08 12:09

Daren Thomas


People also ask

How do you evaluate an AC expression?

C Expression EvaluationThe operator with higher precedence is evaluated first and the operator with the least precedence is evaluated last. An expression is evaluated based on the precedence and associativity of the operators in that expression.

What is C evaluation?

Expression evaluation in C is used to determine the order of the operators to calculate the accurate output. Arithmetic, Relational, Logical, and Conditional are expression evaluations in C.

How do you evaluate an expression explain with example?

To evaluate an algebraic expression, you have to substitute a number for each variable and perform the arithmetic operations. In the example above, the variable x is equal to 6 since 6 + 6 = 12. If we know the value of our variables, we can replace the variables with their values and then evaluate the expression.


1 Answers

Old topic, but considering this is one of the first threads showing up when googling, here is an updated solution.

You can use Roslyn's new Scripting API to evaluate expressions.

If you are using NuGet, just add a dependency to Microsoft.CodeAnalysis.CSharp.Scripting. To evaluate the examples you provided, it is as simple as:

var result = CSharpScript.EvaluateAsync("1 + 3").Result; 

This obviously does not make use of the scripting engine's async capabilities.

You can also specify the evaluated result type as you intended:

var now = CSharpScript.EvaluateAsync<string>("System.DateTime.Now.ToString()").Result; 

To evaluate more advanced code snippets, pass parameters, provide references, namespaces and whatnot, check the wiki linked above.

like image 187
Ridkuma Avatar answered Oct 06 '22 01:10

Ridkuma