Skip to content

Instantly share code, notes, and snippets.

@keith9820
Created July 13, 2016 21:16
Show Gist options
  • Save keith9820/1e509ca673ea4a7cc971d9ee0cea690a to your computer and use it in GitHub Desktop.
Save keith9820/1e509ca673ea4a7cc971d9ee0cea690a to your computer and use it in GitHub Desktop.
C# Eval method
private static object Eval(string __code)
{
var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });
var p = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, null, true);
p.GenerateInMemory = true;
p.GenerateExecutable = false;
CompilerResults r = csc.CompileAssemblyFromSource(p, "using System; class p {public static object c(){"+__code+"}}");
if (r.Errors.Count > 0)
{
r.Errors.Cast<CompilerError>().ToList().ForEach(error => Console.WriteLine(error.ErrorText));
return null;
}
System.Reflection.Assembly a = r.CompiledAssembly;
MethodInfo o = a.CreateInstance("p").GetType().GetMethod("c");
return o.Invoke(o, null);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment