Using the c# runtime compiler to evaluate simple maths formulas

By pete rainbow

A simple class to demonstrate the usage of the c# runtime compiler and also a simple reflection execution of a static method

    public class ExecuteSimpleFormula
    {
         public static double Eval(string formula)
        {
             string className = "RunnerClass" + DateTime.Now.Ticks;
            
            string codeStr = @"
                 public static class " + className + @"  
                 {
                     public static double Eval()
                     {
                          return " + formula + @";
                       }
                }";

           var codeProvider = new CSharpCodeProvider();
           var results = codeProvider.CompileAssemblyFromSource(new CompilerParameters(), codeStr);


             if (results.Errors.HasErrors)
            {
                 foreach (CompilerError msg in results.Errors)
                   Debug.WriteLine(msg);
            }
            else
            {
               var myEvalMethod = results.CompiledAssembly.GetType(className).GetMethod("Eval", System.Reflection.BindingFlags.Static | BindingFlags.Public);
                 Object value = myEvalMethod.Invoke(null, null);

                 return (double)value;
            }
            return double.NaN;
        }

         public static void Test()
        {
             ExecuteSimpleFormula.Eval("2*3 + 6*7");
        }
     }

Using the c# runtime compiler to evaluate simple maths formulas  (2796 Views)