• Programmatically saying hello to the C# compiler

    by  • September 24, 2011 • .Net, Programming • 0 Comments

    Like most of the best features of the .Net Framework, access to the C# and language compilers and syntax parsers are hidden away. These provide you the ability to traverse language independent code trees (remember .Net languages all compile down to MSIL) and allow compilation of .Net languages. For this I will show you have to access the C# compiler.

    Access to the Compiler is made from the ICodeCompiler compiler execution Interface. Originally the C# specific class that implements this interface and provides access to the C# Code compiler and generator is CSharpCodeProvider. This class however is now depreciated and is replaced with CodeDomProvider which allows the user to specify which language they want to use.

    CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
    ICodeCompiler icc = codeProvider.CreateCompiler();

    Now that we have a Code Compiler for our language of choice, C# in this case, we can set parameters and then begin compiling code.

    System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
    parameters.GenerateExecutable = true;
    parameters.OutputAssembly = Output;
    CompilerResults results = icc.CompileAssemblyFromSource(parameters,SourceString);

    The parameters above that we choose tell the compiler to build an executable rather than a DLL and we want the Assembly to be output to disk. CompileAssemblyFromSource is where all the cool stuff happens. We can use the return value stored in results to determine if any errors or warnings occurred during compilation.

    if (results.Errors.Count > 0)
        foreach(CompilerError CompErr in results.Errors)
          //...Error handling code


    Software engineer. Tea drinker


    Leave a Reply

    Your email address will not be published. Required fields are marked *