// 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.Reflection; using System.CodeDom.Compiler; using Microsoft.CSharp; using Microsoft.JScript; namespace E { public interface ICS { double Eval(); } public class CS { private static int n = 0; public static double Eval(string expr) { n++; string cn = "C" + n; string src = "using System; using E; public class " + cn + " : ICS { public double Eval() { return " + expr + "; } }"; CodeDomProvider comp = new CSharpCodeProvider(); CompilerParameters param = new CompilerParameters(); param.GenerateInMemory = true; param.ReferencedAssemblies.Add("System.dll"); param.ReferencedAssemblies.Add(System.Reflection.Assembly.GetExecutingAssembly().Location); CompilerResults res = comp.CompileAssemblyFromSource(param, src); Assembly asm = res.CompiledAssembly; ICS o = (ICS)asm.CreateInstance(cn); return o.Eval(); } } public interface IJS { double Eval(string expr); } public class JS { private static IJS engine; static JS() { string src = "import System; import E; public class C implements IJS { public function Eval(expr : String) : Double { return eval(expr); } }"; CodeDomProvider comp = new JScriptCodeProvider(); CompilerParameters param = new CompilerParameters(); param.GenerateInMemory = true; param.ReferencedAssemblies.Add("System.dll"); param.ReferencedAssemblies.Add(System.Reflection.Assembly.GetExecutingAssembly().Location); CompilerResults res = comp.CompileAssemblyFromSource(param, src); Assembly asm = res.CompiledAssembly; engine = (IJS)asm.CreateInstance("C"); } public static double Eval(string expr) { return engine.Eval(expr); } } public class Program { private const int NCS = 100; private const int NJS = 10000; public static void Main(string[] args) { Console.WriteLine(CS.Eval("2+2+2")); Console.WriteLine(JS.Eval("2+2+2")); DateTime dt1 = DateTime.Now; for(int i = 0; i < NCS; i++) { if(CS.Eval("2+2+2") != 6) { throw new Exception("Ooops in C#"); } } DateTime dt2 = DateTime.Now; Console.WriteLine("C# : " + (dt2 - dt1).TotalSeconds/NCS); DateTime dt3 = DateTime.Now; for(int i = 0; i < NJS; i++) { if(JS.Eval("2+2+2") != 6) { throw new Exception("Ooops in JScript"); } } DateTime dt4 = DateTime.Now; Console.WriteLine("JScript : " + (dt4 - dt2).TotalSeconds/NJS); } } }