Created
January 16, 2016 21:57
-
-
Save JoshVarty/0ee65153b5885d275b5c to your computer and use it in GitHub Desktop.
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
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