How to evaluate (((2+5)*1000)/((30-12)*6)) at runtime in C#?

Rajnilari2015
Posted by Rajnilari2015 under C# category on | Points: 40 | Views : 1161
The below code will help to do so

using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Data;
using System.Reflection;
using System.Text;

namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
// object result = Eval("((10 + 12)*5)"); //result 110
object result = Eval("(((2+5)*1000)/((30-12)*6))"); //result 64
}

private static 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));
}

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;

}
}
}

Comments or Responses

Login to post response