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.
Happy coding...
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.
- 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.
- GetSourceCode() This method simply returns sample source code to compile.Can be replaced by any other code snippet.
- GetSyntaxTree() This method parses the input code and creates the CSharpSyntaxTree.
- GetReferences() Compilation always needs what are the references needed. Here its very basic as we are not using any advanced features.
- Compile() 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.
- ShowDiagnostics() This method shows any warnings in compilation.
Happy coding...
No comments:
Post a Comment