Created
September 1, 2018 07:59
-
-
Save fearofcode/3abb41d0b1a60194765f1fdd81da5269 to your computer and use it in GitHub Desktop.
Simple working example of dynamically compiling a string of valid C# code and calling it
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.CodeDom.Compiler; | |
using Microsoft.CSharp; | |
using System.Reflection; | |
namespace dynamiccompilation | |
{ | |
class Program | |
{ | |
static CompilerParameters CompilerParams = new CompilerParameters | |
{ | |
GenerateInMemory = true, | |
TreatWarningsAsErrors = false, | |
GenerateExecutable = false | |
}; | |
static string[] references = { "System.dll", "mscorlib.dll" }; | |
static CSharpCodeProvider provider = new CSharpCodeProvider(); | |
static void Main(string[] args) | |
{ | |
CompilerParams.ReferencedAssemblies.AddRange(references); | |
CompileAndRun(new string[] { | |
"using System;" + | |
"namespace dynamiccompilation" + | |
"{" + | |
" public class DynamicExample" + | |
" {" + | |
" static public void Main()" + | |
" {" + | |
" System.Console.WriteLine(\"The time is now {0}.\", System.DateTime.Now);" + | |
" }" + | |
" }" + | |
"}"}); | |
Console.ReadKey(); | |
} | |
static void CompileAndRun(string[] code) | |
{ | |
DateTime start = DateTime.Now; | |
CompilerResults compile = provider.CompileAssemblyFromSource(CompilerParams, code); | |
DateTime compilationFinished = DateTime.Now; | |
if (compile.Errors.HasErrors) | |
{ | |
foreach (CompilerError ce in compile.Errors) | |
{ | |
Console.WriteLine(ce.ToString()); | |
} | |
Console.ReadKey(); | |
return; | |
} else | |
{ | |
Module module = compile.CompiledAssembly.GetModules()[0]; | |
module | |
.GetType("dynamiccompilation.DynamicExample") | |
.GetMethod("Main") | |
.Invoke(null, new object[] { }); | |
} | |
DateTime executionFinished = DateTime.Now; | |
Console.WriteLine($"Compile time: {compilationFinished - start}"); | |
Console.WriteLine($"Execution time: {executionFinished - compilationFinished}"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment