Search code examples
c#runtime-compilation

Compile and run dynamic code, without generating EXE?


I was wondering if it was possible to compile, and run stored code, without generating an exe or any type of other files, basically run the file from memory.

Basically, the Main application, will have some stored code (code that will potentially be changed), and it will need to compile the code, and execute it. without creating any files.

creating the files, running the program, and then deleting the files is not an option. the compiled code will need to be ran from memory.

code examples, or pointers, or pretty much anything is welcome :)


Solution

  • using (Microsoft.CSharp.CSharpCodeProvider foo = 
               new Microsoft.CSharp.CSharpCodeProvider())
    {
        var res = foo.CompileAssemblyFromSource(
            new System.CodeDom.Compiler.CompilerParameters() 
            {  
                GenerateInMemory = true 
            }, 
            "public class FooClass { public string Execute() { return \"output!\";}}"
        );
    
        var type = res.CompiledAssembly.GetType("FooClass");
    
        var obj = Activator.CreateInstance(type);
    
        var output = type.GetMethod("Execute").Invoke(obj, new object[] { });
    }
    

    This compiles a simple class from the source code string included, then instantiates the class and reflectively invokes a function on it.