blog: Compiling C# code at runtime

The following is a minimal example of compiling C# code stored in a string at runtime. The result is a full-fledged assembly, which can be accessed and used via reflection.

using System.Reflection;
using System.CodeDom;
using System.CodeDom.Compiler;

public class Metaprogramming {
  public static void Main() {
    var test = @"

      using System.IO;
      namespace Test {

        public class Foobar{
          public static void Main() {
            using (var writer = File.CreateText(""compiletest.txt"")) {

    var csc = CodeDomProvider.CreateProvider("CSharp");
    var options = new CompilerParameters();
    var res = csc.CompileAssemblyFromSource(options, test);
    var type = res.CompiledAssembly.GetType("Test.Foobar");
    type.GetMethod("Main").Invoke(null, null);

Running the above code will result in a file compiletest.txt, which was created by the code stored in the string test.

% ./example.exe
% cat compiletest.txt

If you need references to other assemblies for your code, you can pass those assemblies to the compiler parameters:

Posted in programming
2017-03-18 13:06 UTC