Quick and Dirty Eval for C#

Introduction

“Eval is evil” is a well known phrase and with good reason. Allowing arbitrary code execution opens the doors for [hacker stereotype] to pwn your beautiful application.

Quick and Dirty Eval for C#

Evil Programmers

In many situations the need to reach out to eval is not even needed, its mostly a lazy way out. The price of eval is very high, you pay in terms of speed and security as well as increased debugging complexity.

“eval is Evil: The eval function is the most misused feature of JavaScript. Avoid it”

 Douglas Crockford in JavaScript: The Good Parts

Of course JavaScript is not the only language to have eval, PHP and many other languages have the ability to evaluate code from strings. The evil uses aside, the ability to evaluate code on the “fly” does open up some cool possibilities such as meta programing.

When it comes to C# however the eval function doesn’t exist (probably a good thing). However I recently needed to visit the dark side, most examples of C# eval are quite verbose, but I managed to put together a fat free version. Its quick and its dirty and you probably shouldn’t use it but in times of desperation…

Quick and Dirty C# eval in 8 lines:

    {
        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);
    }
comments powered by Disqus