Refactoring Roslyn like a boss

Roslyn is a platform for the analysis of the C# language. We can use it (among other

Refactoring like a boss with Roslyn
Roslyn is a platform for the analysis of the C# language. We can use it (among other things) to write code refactoring tools. Here is an example of how use Roslyn to rewrite implicit local variables statements (using the var keyword) to make declarations explicit.

Obtained result

Using code shown in this article, we convert the following sample code:



If we use Microsoft’s open source implementation platform, it is important to add the necessary assemblies to the project.json:

Syntax Factory

The Syntax Factory class is used to programmatically create code. In this example, we need to create a statement of the LocalDeclarationStatement type. For example, to create the code “int x;”:

What we do is:

  • Indicate the type as a predefined type int (IntKeyword).
  • Indicate the identifier, in this case “x” (Identifier(“x”)).
  • Format the code (NormalizeWhitespace()).

SyntaxTree and CSharpSyntaxRewriter visitor

The syntax tree is a parsed representation obtained from a C# code. Roslyn provides us with a visitor to visit the syntax tree nodes and nodes that we want to overwrite. In our case, we will visit all the nodes of LocalDeclarationStatementSyntax type and change the var for the explicit type.

To obtain the SyntaxTree of a C#, we use CSharpSyntaxTree.ParseText:

Then, we create the visitor that visits all nodes of LocalDeclarationStatementSyntax type:

If we are returning null, we delete the node. Then we will complete the visitor to solve the problem posed.

Semantic Model

To obtain the type of data corresponding to the variable declaration, we must analyze the code to a semantic level (not only syntactic), therefore we will need to obtain the SemanticModel corresponding to a SyntaxTree:

Then, to obtain the type of a variable declaration, we do the following:

Where node is a node of the LocalDeclarationStatementSyntax type.

Var Rewriter

Finally, putting all together, we can complete the visitor that rewrites the implicit statements into explicit:

Here is what we do:

  • Get the type (var type) of the implicit statement (without namespaces), for example: List<string> instead of Collection.Generic.List<string>.
  • Create a LocalDeclarationStatement with the corresponding type and keep the rest equal to the node visited (WithVariables(node.Declaration.Variables)).
  • Keep trivia (format, blanks) of the same node (WithTriviaFrom(node)).
  • Return the declaration that will be replaced by the visited node.

Full Code

You can see the entire project in github’s repository. Just in case, here it is:


Share this articleShare on LinkedInTweet about this on TwitterShare on FacebookShare on Google+Email this to someone
Go Back