Compiling .Net code at runtime

Compiling code at run-time in .Net is surprisingly easy, your code just have to be valid in order for the framework to compile and generate the assemblies and or the executable.

The following method (CsharpCompiler) accepts the following parameters string sourceCode, string outputDllName = @"C:\temp\dynamicCompile.dll", params string[] additionalAssemblies where sourceCode is valid C# code, outputDllName is the default name and path of the generated dll and additionalAssemblies to be used when including any additioal assemblies your code may need to compile.The method returns a CompilerResult object in case you need to further work with the result of the method execution.

CompilerTools Class:

public static class CompilerTools
   {
       public static CompilerResults CSharpCompile(string sourceCode, string outputDllName = @"C:\temp\dynamicCompile.dll", params string[] additionalAssemblies)
       {
           var systemDlls = new List<string>
       {
           "mscorlib.dll",
           "System.dll",
           "System.Core.dll",
       };
           if (additionalAssemblies.Any())
           {
               systemDlls.AddRange(additionalAssemblies);
           }
           /*Debugger.IsAttached is used to only include debug info for the created assembly
            when the code is executed from a development environment*/
           var compilerParameters = new CompilerParameters(systemDlls.ToArray(), outputDllName, Debugger.IsAttached)
           {
               TreatWarningsAsErrors = true, //You should always treat warning as potential problems in code
               WarningLevel = 0,
               GenerateExecutable = false, //We don't need an exe here
               GenerateInMemory = true,
               CompilerOptions = "/optimize+ /platform:anycpu"
           };
           var options = new Dictionary<string, string> {
            { "CompilerVersion", "v4.0" } //both framework 4 and 4.5 use the same compiler version
            };
           var compiler = new CSharpCodeProvider(options);
           var result = compiler.CompileAssemblyFromSource(compilerParameters, sourceCode);
           if (result.Errors.HasErrors)
           {
               foreach (var error in result.Errors)
               {
                   Console.WriteLine("Compiler error {0}", error);
               }
           }
           return result;
       }
   }

Usage example:

            var code = @" using System;
                          using System.Threading.Tasks;
                            namespace Company.Department.Application
                            {
                                    public class MyClass
                                    {
                                        static async Task Foo(Action action)
                                        {
                                            await Task.Run(action);
                                        }
                                    }
                              }";
CompilerTools.CSharpCompile(code, "System.XML.dll", @"E:\temp\TestClass11.dll");

compiling code on run time can be extremely helpful when you are working with templates or plugin driven environments where users create their own entities.

Add comment