title: How can I evaluate a C# expression dynamically?
body: <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>