C# - Runtime compilation

By , 8/19/2012
(1 ratings)
Sometimes it can be useful to compile code at runtime and use it afterwards.

Examples would be a script implementation or evaluation of formulas.

The example shown in the snippet is kept simple and only concatenates the input string with the method itself.

This works like a normal compilation, just the completed assembly is directly kept in memory and is accessible via reflection.

Author: Günther Foidl, translation by Michael List
using System;
using System.CodeDom.Compiler;
using System.Reflection;
using System.Text;

namespace Compile_code_at_runtime
    class Program
        static void Main(string[] args)
            Console.Write("Enter text -> ");
            string textInput = Console.ReadLine();

            Assembly assembly = CompileCode(textInput);
            object o = assembly.CreateInstance("gfoidl.Code.Test");
            Type t = o.GetType();
            MethodInfo mi = t.GetMethod("Result");
            object result = mi.Invoke(o, new object[] { textInput });

        public static Assembly CompileCode(string inputCode)
            CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");

            CompilerParameters cp = new CompilerParameters();
            cp.CompilerOptions = "/t:library";
            cp.GenerateInMemory = true;

            StringBuilder sb = new StringBuilder();
            sb.AppendLine(@"using System;");
            sb.AppendLine(@"namespace gfoidl.Code{");
            sb.AppendLine(@"public class Test{");
            sb.AppendLine(@"public string Result(string input){");
            sb.AppendLine(@"return input + ""\t"" + input;");

            CompilerResults cr =
                provider.CompileAssemblyFromSource(cp, sb.ToString());

            if (cr.Errors.Count > 0)
                return null;

            return cr.CompiledAssembly;



Log in, to comment!