Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiling .NET code in .NET 4?

I remember when .NET 4 was in beta there was a video of a developer that made a command-line app that he could type C# code into and it would compile the code on the fly. The idea was that the compiler was now available in the .NET language.

Anyone recall where this is? I need to create an application with a small macro language and I would love to use C# as that macro language, but I don't know where to find this library..

like image 909
Kelly Avatar asked Jun 24 '10 15:06

Kelly


1 Answers

You can use the CSharpCodeProvider class to compile assemblies at runtime.

You'll need to make a boilerplate template to wrap the macro commands in a static method in a class.

For example:

static readonly Assembly[] References = new[] { typeof(Enumerable).Assembly, typeof(Component).Assembly };
public Action CompileMacro(string source) {
    var options = new CompilerParameters(References.Select(a => a.Location).ToArray()) {
        GenerateInMemory = true
    };
    string fullSource = @"public static class MacroHolder { public static void Execute() { \r\n" + source + "\r\n} }";
    try {
        var compiler = new CSharpCodeProvider(new Dictionary<string, string> { { "CompilerVersion", "v4.0" } });

        var results = compiler.CompileAssemblyFromSource(options, fullSource);

        if (results.Errors.Count > 0)
            throw new InvalidOperationException(String.Join(
                Environment.NewLine, 
                results.Errors.Cast<CompilerError>().Select(ce => ce.ErrorText)
            ));

        return (Action)Delegate.CreateDelegate(
            typeof(Action),
            results.CompiledAssembly.GetType("MacroHolder").GetMethod("Execute")
        );
    } finally { options.TempFiles.Delete(); }
}
like image 160
SLaks Avatar answered Sep 22 '22 10:09

SLaks