Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top