Skip to content

Instantly share code, notes, and snippets.

@fearofcode
Created September 1, 2018 07:59
Show Gist options
  • Save fearofcode/3abb41d0b1a60194765f1fdd81da5269 to your computer and use it in GitHub Desktop.
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
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