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
Translate to VB
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 });
            Console.WriteLine(result);

            Console.ReadKey();
        }
        //---------------------------------------------------------------------
        public static Assembly CompileCode(string inputCode)
        {
            CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");

            CompilerParameters cp = new CompilerParameters();
            cp.ReferencedAssemblies.Add("system.dll");
            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;");
            sb.AppendLine(@"}}}");

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

            if (cr.Errors.Count > 0)
            {
                Console.WriteLine(cr.Errors[0].ErrorText);
                return null;
            }

            return cr.CompiledAssembly;
        }
    }
}

Comments

 

Log in, to comment!