using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using System.Reflection; internal class Program { private static void Main() { string code = "internal class Program { private static void Main() { System.Console.WriteLine(\"ethical.blue Magazine\"); } }"; var root = Path.GetDirectoryName(typeof(object).Assembly.Location) ?? string.Empty; var tree = SyntaxFactory.ParseSyntaxTree(code); var compilation = CSharpCompilation.Create(Path.GetRandomFileName()) .WithOptions(new CSharpCompilationOptions(OutputKind.ConsoleApplication, optimizationLevel: OptimizationLevel.Release)) .AddReferences(MetadataReference.CreateFromFile(Path.Combine(root, "System.dll"))) .AddReferences(MetadataReference.CreateFromFile(Path.Combine(root, "System.Runtime.dll"))) .AddReferences(MetadataReference.CreateFromFile(typeof(object).Assembly.Location)) .AddReferences(MetadataReference.CreateFromFile(typeof(Console).Assembly.Location)) .AddSyntaxTrees(tree); using MemoryStream ILCodeStream = new(); var result = compilation.Emit(ILCodeStream); if (result.Success) { var assembly = Assembly.Load(ILCodeStream.ToArray()); _ = assembly.EntryPoint?.Invoke(null, []); } #if DEBUG foreach (var error in result.Diagnostics) Console.WriteLine(error.ToString()); #endif } }