
上QQ阅读APP看书,第一时间看更新
How to do it...
- Let's download the SDK and extend the compiler, installing the VS extension, .NET Compiler Platform SDK, by going through the Tools | Extensions and Updates menu, searching for Roslyn SDK:

- We can now download the .NET Compiler Platform SDK templates as a .vsix file, which gives us all the available project templates to create an analyzer:

- We can now use the template projects in New Project | Visual C# | Extensibility | Stand-Alone Code Analysis Tool.
- Let's open a new console application for an Extensibility project:

This console application will access the Roslyn API, with which we will be able to use the Syntax Tree API.
- Let's now create a SyntaxTree, which is simply a class represented by a tree structure of elements using the SyntaxTree type:

This type has a method named ParseText, which will parse a string where a class is written:

- Let's write this piece of code:

The GetRoot method will give us the root of the tree.
- Using Ctrl + F5, we see the result.
- Now, thanks to the SyntaxFactory type, let's create the same class by creating a SyntaxTree with the Syntax API:

- With the SyntaxFactory.ClassDeclaration method, we create the class name:

- The WithMembers method allows us to create members of this class:

- Now we create a method named Bar with void as the return type.
- The WithBody method and its SyntaxFactory.Block parameter help us to add an empty block to the Bar method:

- The NormalizeWithespace method will add indentation and spaces to make this class more readable:

- Let's press Ctrl + F5 to see the result of our code, putting the variable representing the Syntax Tree as the parameter of Console.WriteLine:
