views:

438

answers:

1

I managed to create a class using CodeDom and add a single method to that class. Now, is there a way to, having constructed the CodeCompileUnit instance, compile the code and invoke the generated method? The method invocation has to be done in the same context as the code generation.

+3  A: 

Taken from a friend of mine's blog:

    CSharpCodeProvider codeProvider = new CSharpCodeProvider();
    codeProvider.GenerateCodeFromNamespace(codeNamespace, new StringWriter(), new CodeGeneratorOptions());

    CompilerParameters param = new CompilerParameters(assemblyReferences);
    param.GenerateExecutable = false;
    param.GenerateInMemory = true;
    param.TreatWarningsAsErrors = false;
    param.WarningLevel = 4;

    CompilerResults results = codeProvider.CompileAssemblyFromDom(param, compileUnit);
    Assembly assembly = results.CompiledAssembly;

    Type[] types = assembly.GetExportedTypes();

You can then use reflection on the types to create an instance of the type you want and execute whatever method you want.

Santiago Palladino