<p>I would like to do the equivalent of:</p>

<pre><code>object result = Eval("1 + 3");
string now    = Eval("System.DateTime.Now().ToString()") as string
</code></pre>

<p>Following Biri s <a href="http://www.codeproject.com/KB/cs/evalcscode.aspx" rel="noreferrer">link</a>, I got this snippet (modified to remove obsolete method <code>ICodeCompiler.CreateCompiler()</code>:</p>

<pre><code>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 &gt; 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;

}  
</code></pre>

[{'answer_id': 54339, 'author': 'JJJ', 'author_id': 5547, 'author_profile': 'https://Stackoverflow.com/users/5547', 'pm_score': 1, 'selected': False, 'text': '<blockquote>\n  <p>What are the performance implications of doing this?</p>\n</blockquote>\n\n<p>We use a system based on something like the above mentioned, where each C# script is compiled to an in-memory assembly and executed in a separate AppDomain. There\'s no caching system yet, so the scripts are recompiled every time they run. I\'ve done some simple testing and a very simple "Hello World" script compiles in about 0.7 seconds on my machine, including loading the script from disk. 0.7 seconds is fine for a scripting system, but might be too slow for responding to user input, in that case a dedicated parser/compiler like Flee might be better.</p>\n\n<pre><code>using System;\npublic class Test\n{\n    static public void DoStuff( Scripting.IJob Job)\n    {\n        Console.WriteLine( "Heps" );\n    }\n}\n</code></pre>\n'}, {'answer_id': 286189, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>Looks like there is also a way of doing it using RegEx and XPathNavigator to evaluate the expression. I did not have the chance to test it yet but I kind of liked it because it did not require to compile code at runtime or use libraries that could not be available.</p>\n\n<p><a href="http://www.webtips.co.in/c/evaluate-function-in-c-net-as-eval-function-in-javascript.aspx" rel="nofollow noreferrer">http://www.webtips.co.in/c/evaluate-function-in-c-net-as-eval-function-in-javascript.aspx</a></p>\n\n<p>I\'ll try it and tell later if it worked. I also intend to try it in Silverlight, but it is too late and I\'m almost asleep to do it now.</p>\n'}, {'answer_id': 4050198, 'author': 'Rudolf_Abel', 'author_id': 491038, 'author_profile': 'https://Stackoverflow.com/users/491038', 'pm_score': 2, 'selected': False, 'text': '<pre><code>using System;\nusing Microsoft.JScript;\nusing Microsoft.JScript.Vsa;\nusing Convert = Microsoft.JScript.Convert;\n\nnamespace System\n{\n    public class MathEvaluator : INeedEngine\n    {\n        private VsaEngine vsaEngine;\n\n        public virtual String Evaluate(string expr)\n        {\n            var engine = (INeedEngine)this;\n            var result = Eval.JScriptEvaluate(expr, engine.GetEngine());\n\n            return Convert.ToString(result, true);\n        }\n\n        VsaEngine INeedEngine.GetEngine()\n        {\n            vsaEngine = vsaEngine ?? VsaEngine.CreateEngineWithType(this.GetType().TypeHandle);\n            return vsaEngine;\n        }\n\n        void INeedEngine.SetEngine(VsaEngine engine)\n        {\n            vsaEngine = engine;\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 6301451, 'author': 'xnaterm', 'author_id': 445334, 'author_profile': 'https://Stackoverflow.com/users/445334', 'pm_score': 0, 'selected': False, 'text': '<p>While C# doesn\'t have any support for an Eval method natively, I have a C# eval program that does allow for evaluating C# code. It provides for evaluating C# code at runtime and supports many C# statements. In fact, this code is usable within any .NET project, however, it is limited to using C# syntax. Have a look at my website, <a href="http://csharp-eval.com" rel="nofollow">http://csharp-eval.com</a>, for additional details.</p>\n'}, {'answer_id': 14761604, 'author': 'Davide Icardi', 'author_id': 209727, 'author_profile': 'https://Stackoverflow.com/users/209727', 'pm_score': 5, 'selected': False, 'text': '<p>I have written an open source project, <a href="https://github.com/davideicardi/DynamicExpresso/" rel="noreferrer">Dynamic Expresso</a>, that can convert text expression written using a C# syntax into delegates (or expression tree). Text expressions are parsed and transformed into <a href="http://msdn.microsoft.com/en-us/library/bb397951.aspx" rel="noreferrer">Expression Trees</a> without using compilation or reflection.</p>\n\n<p>You can write something like:</p>\n\n<pre><code>var interpreter = new Interpreter();\nvar result = interpreter.Eval("8 / 2 + 2");\n</code></pre>\n\n<p>or</p>\n\n<pre><code>var interpreter = new Interpreter()\n                .SetVariable("service", new ServiceExample());\n\nstring expression = "x &gt; 4 ? service.aMethod() : service.AnotherMethod()";\n\nLambda parsedExpression = interpreter.Parse(expression, \n                        new Parameter("x", typeof(int)));\n\nparsedExpression.Invoke(5);\n</code></pre>\n\n<p>My work is based on Scott Gu article <a href="http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx" rel="noreferrer">http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx</a> .</p>\n'}, {'answer_id': 43630318, 'author': 'Ridkuma', 'author_id': 5466644, 'author_profile': 'https://Stackoverflow.com/users/5466644', 'pm_score': 5, 'selected': False, 'text': '<p>Old topic, but considering this is one of the first threads showing up when googling, here is an updated solution.</p>\n\n<p>You can use <a href="https://github.com/dotnet/roslyn/wiki/Scripting-API-Samples" rel="noreferrer">Roslyn\'s new Scripting API to evaluate expressions</a>.</p>\n\n<p>If you are using NuGet, just add a dependency to <a href="https://www.nuget.org/packages/Microsoft.CodeAnalysis.CSharp.Scripting/" rel="noreferrer">Microsoft.CodeAnalysis.CSharp.Scripting</a>.\nTo evaluate the examples you provided, it is as simple as:</p>\n\n<pre><code>var result = CSharpScript.EvaluateAsync("1 + 3").Result;\n</code></pre>\n\n<p>This obviously does not make use of the scripting engine\'s async capabilities. </p>\n\n<p>You can also specify the evaluated result type as you intended: </p>\n\n<pre><code>var now = CSharpScript.EvaluateAsync&lt;string&gt;("System.DateTime.Now.ToString()").Result;\n</code></pre>\n\n<p>To evaluate more advanced code snippets, pass parameters, provide references, namespaces and whatnot, check the wiki linked above.</p>\n'}, {'answer_id': 52685808, 'author': 'cdiggins', 'author_id': 184528, 'author_profile': 'https://Stackoverflow.com/users/184528', 'pm_score': 4, 'selected': False, 'text': '<p>If you specifically want to call into code and assemblies in your own project I would advocate using the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.codedom.compiler.codedomprovider?view=netframework-4.7.2" rel="noreferrer">C# CodeDom CodeProvider</a>. </p>\n\n<p>Here is a list of the most popular approaches that I am aware of for evaluating string expressions dynamically in C#. </p>\n\n<h2>Microsoft Solutions</h2>\n\n<ul>\n<li><a href="https://learn.microsoft.com/en-us/dotnet/api/system.codedom.compiler.codedomprovider?view=netframework-4.7.2" rel="noreferrer">C# CodeDom CodeProvider</a>: \n\n<ul>\n<li>See <a href="https://stackoverflow.com/questions/5766373/how-does-linqpad-compile-code">How LINQ used to work</a> and this <a href="https://www.codeproject.com/Articles/11939/Evaluate-C-Code-Eval-Function" rel="noreferrer">CodeProject article</a></li>\n</ul></li>\n<li><a href="https://github.com/dotnet/roslyn" rel="noreferrer">Roslyn</a>:\n\n<ul>\n<li>See this <a href="https://joshvarty.com/2016/01/16/learn-roslyn-now-part-16-the-emit-api" rel="noreferrer">article on Rosly Emit API</a> and this <a href="https://stackoverflow.com/a/43630318/184528">StackOverflow answer</a></li>\n</ul></li>\n<li><a href="http://msdn.microsoft.com/en-us/library/system.data.datatable.compute.aspx" rel="noreferrer">DataTable.Compute</a>:\n\n<ul>\n<li>See this <a href="https://stackoverflow.com/a/12431343/184528">answer on StackOverflow</a></li>\n</ul></li>\n<li><a href="https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.htmldocument.invokescript?view=netframework-4.7.2" rel="noreferrer">Webbrowser.Document.InvokeScript</a>\n\n<ul>\n<li>See this <a href="https://stackoverflow.com/questions/7322420/calling-javascript-object-method-using-webbrowser-document-invokescript">StackOverflow question</a></li>\n</ul></li>\n<li><a href="https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.databinder.eval?redirectedfrom=MSDN&amp;view=netframework-4.7.2#overloads" rel="noreferrer">DataBinder.Eval</a></li>\n<li><a href="https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-6.0/aa227400(v=vs.60)" rel="noreferrer">ScriptControl</a>\n\n<ul>\n<li>See <a href="https://stackoverflow.com/questions/12431286/calculate-result-from-a-string-expression-dynamically/12431435#12431435">this answer on StackOverflow</a> and <a href="https://stackoverflow.com/questions/16075775/calling-the-javascript-functions-inside-c-sharp-for-a-64-bit-project?noredirect=1&amp;lq=1">this question</a></li>\n</ul></li>\n<li>Executing PowerShell:\n\n<ul>\n<li>See <a href="https://www.codeproject.com/Articles/18229/How-to-run-PowerShell-scripts-from-C" rel="noreferrer">this CodeProject article</a></li>\n</ul></li>\n</ul>\n\n<h2>Non-Microsoft solutions (not that there is anything wrong with that)</h2>\n\n<ul>\n<li>Expression evaluation libraries:\n\n<ul>\n<li><a href="https://github.com/mparlak/Flee" rel="noreferrer">Flee</a></li>\n<li><a href="https://github.com/davideicardi/DynamicExpresso/" rel="noreferrer">DynamicExpresso</a></li>\n<li><a href="https://archive.codeplex.com/?p=ncalc" rel="noreferrer">NCalc</a></li>\n<li><a href="https://github.com/codingseb/ExpressionEvaluator" rel="noreferrer">CodingSeb.ExpressionEvaluator</a></li>\n<li><a href="https://github.com/zzzprojects/Eval-Expression.NET" rel="noreferrer">Eval-Expression.NET</a></li>\n</ul></li>\n<li>Javascript interpreter\n\n<ul>\n<li><a href="https://github.com/sebastienros/jint" rel="noreferrer">Jint</a></li>\n</ul></li>\n<li>To execute real C#\n\n<ul>\n<li><a href="https://github.com/oleg-shilo/cs-script" rel="noreferrer">CS-Script</a></li>\n</ul></li>\n<li>Roll your own a language building toolkit like:\n\n<ul>\n<li><a href="https://archive.codeplex.com/?p=irony" rel="noreferrer">Irony</a></li>\n<li><a href="https://www.codeproject.com/Articles/272494/Implementing-Programming-Languages-using-Csharp" rel="noreferrer">Jigsaw</a>    </li>\n</ul></li>\n</ul>\n'}, {'answer_id': 68767842, 'author': 'Binh', 'author_id': 8046877, 'author_profile': 'https://Stackoverflow.com/users/8046877', 'pm_score': 1, 'selected': False, 'text': '<p>I have just written a similar library (<a href="https://github.com/matheval/expression-evaluator-c-sharp" rel="nofollow noreferrer">Matheval</a>) in pure C#.\nIt allows evaluating string and number expression like excel fomular.</p>\n<pre><code>using System;\nusing org.matheval;\n                    \npublic class Program\n{\n    public static void Main()\n    {\n        Expression expression = new Expression(&quot;IF(time&gt;8, (HOUR_SALARY*8) + (HOUR_SALARY*1.25*(time-8)), HOUR_SALARY*time)&quot;);\n        //bind variable\n        expression.Bind(&quot;HOUR_SALARY&quot;, 10);\n        expression.Bind(&quot;time&quot;, 9);\n        //eval\n        Decimal salary = expression.Eval&lt;Decimal&gt;();    \n        Console.WriteLine(salary);\n    }\n}\n</code></pre>\n'}, {'answer_id': 70491393, 'author': 'Venugopal M', 'author_id': 2132005, 'author_profile': 'https://Stackoverflow.com/users/2132005', 'pm_score': 0, 'selected': False, 'text': '<p>There is a nice piece of code here\n<a href="https://www.c-sharpcorner.com/article/codedom-calculator-evaluating-c-sharp-math-expressions-dynamica/" rel="nofollow noreferrer">https://www.c-sharpcorner.com/article/codedom-calculator-evaluating-c-sharp-math-expressions-dynamica/</a></p>\n<p>Download this and make it a class library which may be referenced in your project. This seems to be pretty fast and simple</p>\n<p>Perhaps this could help !</p>\n'}]
['https://Stackoverflow.com/questions/53844', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2260/']