I have written a more compact and efficient version of K. Scott Allen's JScript inline Eval caller from here (https://odetocode.com/articles/80.aspx):
using System;
using System.CodeDom.Compiler;
using Microsoft.JScript;
class JS
{
private delegate object EvalDelegate(String expr);
private static EvalDelegate moEvalDelegate = null;
public static object Eval(string expr)
{
return moEvalDelegate(expr);
}
public static T Eval<T>(string expr)
{
return (T)Eval(expr);
}
public static void Prepare()
{
}
static JS()
{
const string csJScriptSource = @"package _{ class _{ static function __(e) : Object { return eval(e); }}}";
var loParameters = new CompilerParameters() { GenerateInMemory = true };
var loMethod = (new JScriptCodeProvider()).CompileAssemblyFromSource(loParameters, csJScriptSource).CompiledAssembly.GetType("_._").GetMethod("__");
moEvalDelegate = (EvalDelegate)Delegate.CreateDelegate(typeof(EvalDelegate), loMethod);
}
}
Just use it like this:
JS.Eval<Double>("1 + 4 + 5 / 99");
Returns:
5.05050505050505
You could extend it to pass in variable values as well if you wanted to, e.g. pass in a dictionary of names & values. First usage of the static class will take 100-200ms, after that its pretty much instantaneous and doesn't require a separate DLL. Call JS.Prepare() to pre compile to stop the initial delay if you want.