public void EndToEndCompileAndRun()
{
var expression = "6 * 7";
var text = @"public class Calculator
{
public static object Evaluate()
{
return $;
}
}".Replace("$", expression);
var tree = SyntaxTree.ParseText(text);
var compilation = Compilation.Create(
"calc.dll",
options: new CompilationOptions(OutputKind.DynamicallyLinkedLibrary),
syntaxTrees: new[] { tree },
references: new[] { new MetadataFileReference(typeof(object).Assembly.Location) });
Assembly compiledAssembly;
using (var stream = new MemoryStream())
{
EmitResult compileResult = compilation.Emit(stream);
compiledAssembly = Assembly.Load(stream.GetBuffer());
}
Type calculator = compiledAssembly.GetType("Calculator");
MethodInfo evaluate = calculator.GetMethod("Evaluate");
string answer = evaluate.Invoke(null, null).ToString();
Assert.AreEqual("42", answer);
}