Skip to content

Instantly share code, notes, and snippets.

@joeriks
Created December 28, 2012 07:44
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save joeriks/4395547 to your computer and use it in GitHub Desktop.
Save joeriks/4395547 to your computer and use it in GitHub Desktop.
Add a piece of dynamically compiled code in memory with the help of Roslyn. (After this the Greeter class will be available and can be run from example from the immediate window in visual studio).
public static void AddGreeter()
{
AddInmemory("Greeter", @"using System;
class Greeter
{
public string Greet()
{
return ""Hello World"";
}
}");
}
public static void AddInmemory(string inMemoryAssemblyName, string code )
{
var syntaxTree = SyntaxTree.ParseText(code);
var refs = new[] {
MetadataReference.CreateAssemblyReference("mscorlib"),
};
var compilation = Compilation.Create(inMemoryAssemblyName,
syntaxTrees: new[] { syntaxTree },
references: refs,
options: new CompilationOptions(OutputKind.DynamicallyLinkedLibrary));
using (var memoryStream = new MemoryStream())
{
EmitResult result = compilation.Emit(memoryStream);
memoryStream.Flush();
var assembly = Assembly.Load(memoryStream.GetBuffer());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment