Tuesday, June 16, 2015

Using Roslyn to compile C# source code

Below are the steps write a program to compile C# code snippet using Roslyn (Now .Net Compiler Platform)to produce an assembly. Simply saying a C# program compiling another C# program using Roslyn compiler.

The Roslyn nuget version used here is 1.0.0-rc2. This tutorial is organized in zoom in/out fashion.

There are mainly 3 high level steps and they are getting a compilation unit, compiling the same and processing result / diagnostics it produced. The code snippet shows the steps.

  1. GetSimpleCompilation() Now lets look at what is happening in GetSimpleCompilation. As seen in the code we are getting the source code, creating syntax tree out of that then prepare the references needed for the compilation. Finally Creating CSharpCompilation using all the information.
    1. GetSourceCode()
    2. This method simply returns sample source code to compile.Can be replaced by any other code snippet.
    3. GetSyntaxTree()
    4. This method parses the input code and creates the CSharpSyntaxTree.
    5. GetReferences()
    6. Compilation always needs what are the references needed. Here its very basic as we are not using any advanced features.
  2. Compile()
  3. Now its the time to compile. It needs to get the assembly file name to proceed. Since the GetOutpuFilePath() is just simply returning the dll file path, omitting it.
  4. ShowDiagnostics()
  5. This method shows any warnings in compilation.
The compiled assembly can be kept in memory and execute from there. Please refer this link for more details.

Happy coding...

No comments: