// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Collections.Generic; using System.Reflection; using System.CodeDom.Compiler; using Microsoft.CSharp; namespace E { public class DynComp { private static int n = 0; private static Dictionary m = new Dictionary(); public static double Eval(string expr, double x) { object o; if(m.ContainsKey(expr)) { o = m[expr]; } else { n++; string cn = "c" + n; string src = "using System; public class " + cn + " { public static double Eval(double x) { return " + expr + "; } }"; CodeDomProvider comp = new CSharpCodeProvider(); CompilerParameters param = new CompilerParameters(); param.GenerateInMemory = true; param.ReferencedAssemblies.Add("System.dll"); CompilerResults res = comp.CompileAssemblyFromSource(param, src); Assembly asm = res.CompiledAssembly; o = asm.CreateInstance(cn); m.Add(expr, o); } return (double)o.GetType().InvokeMember("Eval", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Static | BindingFlags.InvokeMethod, null, null, new object[] { x }); } } public class MainClass { private const string StrGivenFn = "Math.Pow(x, 3) + (3 * Math.Pow(x, 2)) - (10 * x)"; public static double GivenFn(double x) { return (Math.Pow(x, 3) + (3 * Math.Pow(x, 2)) - (10 * x)); } public static void Main(string[] args) { Console.WriteLine(GivenFn(6)); Console.WriteLine(DynComp.Eval("Math.Pow(x, 3) + (3 * Math.Pow(x, 2)) - (10 * x)", 6)); } } }