Skip to content

Instantly share code, notes, and snippets.

@JoshVarty
Created January 16, 2016 21:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshVarty/0ee65153b5885d275b5c to your computer and use it in GitHub Desktop.
Save JoshVarty/0ee65153b5885d275b5c to your computer and use it in GitHub Desktop.
var tree = CSharpSyntaxTree.ParseText(@"
using System;
public class MyClass
{
public static void Main()
{
Console.WriteLine(""Hello World!"");
Console.ReadLine();
}
}");
var mscorlib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
var compilation = CSharpCompilation.Create("MyCompilation",
syntaxTrees: new[] { tree }, references: new[] { mscorlib });
//Emit to stream
var ms = new MemoryStream();
var emitResult = compilation.Emit(ms);
//Load into currently running assembly. Normally we'd probably
//want to do this in an AppDomain
var ourAssembly = Assembly.Load(ms.ToArray());
var type = ourAssembly.GetType("MyClass");
//Invokes our main method and writes "Hello World" :)
type.InvokeMember("Main", BindingFlags.Default | BindingFlags.InvokeMethod, null, null, null);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment