// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Reflection; using Microsoft.CSharp; namespace E { public interface IDemo { void DoIt(); } public class Program { public static void Exec(string src, string typnam) { CodeDomProvider comp = new CSharpCodeProvider(); CompilerParameters param = new CompilerParameters(); param.GenerateInMemory = true; param.ReferencedAssemblies.Add("System.dll"); param.ReferencedAssemblies.Add("System.Core.dll"); param.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location); CompilerResults res = comp.CompileAssemblyFromSource(param, src); if(res.Errors.Count > 0) { Console.WriteLine(src); foreach(CompilerError ce in res.Errors) { Console.WriteLine(ce); } } Assembly asm = res.CompiledAssembly; IDemo o = (IDemo)asm.CreateInstance(typnam); o.DoIt(); } public static void Main(string[] args) { string c1 = @"using System; using E; namespace Demo { public class C1 : IDemo { public void DoIt() { Console.WriteLine(""Hello from C1""); } } } "; string c2 = @"using System; using E; namespace Demo { public class C2 : IDemo { public void DoIt() { Console.WriteLine(""Hello from C2""); } } } "; Exec(c1, "Demo.C1"); Exec(c2, "Demo.C2"); } } }