3
Reply

Compiling new classes at run-time that inherit from a pre-defined interface

jppollak

jppollak

Feb 11 2005 4:17 PM
2.1k
Hi All, I am using the code below to compile code at run-time to allow the user to create their own classes within the app. The problem I am having is that I would like the classes to inherit from an existing interface so that I can more easily handle them throughout the app. My existing code succesfully creates the code for and compiles the user-defiined classes, and I can then create instances of the classes using Assembly CreateInstance(). What I am not able to do ithus far is get the user-defined classes to succesfully inherit from my interface. I have tried adding the namepsace name of my app to the code being compiled and declaring the class with public class UserClass : MyNameSpace.MyInterface or with public class UserClass : MyInterface but the run-time compiler always raises an error. I have tried reproducing the code for the interface and placing it in user-defined class code, which will allow it to compile. While this seems to work, when I create an instance of the user-defined class, it cannot be cast to the type of the interface, and has clearly not inherited from it. Any suggestions or help would be greatly appreciated! Following is my code for compiling at run-time, in case that helps. Thank you, JP Code for compiling user-defined classes at run-time: ICodeCompiler comp = (new CSharpCodeProvider().CreateCompiler()); CompilerParameters cp = new CompilerParameters(); cp.ReferencedAssemblies.Add("system.dll"); cp.GenerateExecutable = false; cp.GenerateInMemory = true; CompilerResults cr = comp.CompileAssemblyFromSource(cp, code); if (cr.Errors.HasErrors) { StringBuilder error = new StringBuilder(); error.Append("Error Compiling Expression: "); foreach (CompilerError err in cr.Errors) { error.AppendFormat("{0}\n", err.ErrorText); } throw new Exception("Error Compiling Expression: " + error.ToString()); }

Answers (3)