#VS2015 – Delete all comments in a file with #Roslyn


Today is time for some Roslyn code, one more time to delete all the comments in a C# source code file. The step by step on how to create a project of Roslyn, is in the references section in [Roslyn – Creating an enter and initialize field refactoring]. For this sample, we will seek comments elements in a C# source code file. To do this, in the entry point [ComputeRefactorUsing], we’ll look for items with the type SyntaxTrivia. This will run from the current cursor position with the DescentantTrivia() function (line 18)

SyntaxTrivia type elements identify everything that is “not important for the compiler” like jumps of line, comments, etc. (yes, I know you must kill me after the previous statement) In this sample, we will validate that there are elements of the type comments to show the option in the IDE (line 24). Then we will call the command [Remove comments] and associate it with a RemoveAllComents() operation. In this operation, we will again get all elements of type SyntaxTrivia and process them at the level of the document root with the ReplaceTrivia() operation. In one of its overloads, this operation uses 2 parameters to process the replacement.

For this example, we will just replace the line if the Trivia is of the type SingleComment or MultipleComment (line 40). Replace this line by a jump of truck and we can give for closed operation.

In the following video we can see 2 animations, where the 1st one executes the code in the sample, and the 2nd shows a Preview of a replacement eliminated all elements of type SyntaxTrivia.

The sample code can be downloaded from GitHub at https://github.com/elbruno/Blog/tree/master/ElBruno.RemoveComments

Saludos @ Madrid

/El Bruno


– Roslyn https://github.com/dotnet/roslyn/wiki/Roslyn%20Overview#syntax-trivia

– Roslyn – Creating an introduce and initialize field refactoring http://trydis.github.io/2015/01/03/roslyn-code-refactoring/

– Roslyn SyntaxTrivia https://github.com/dotnet/roslyn/wiki/Roslyn%20Overview#syntax-trivia

– Roslyn ReplaceTrivia()http://source.roslyn.io/#Microsoft.CodeAnalysis.CSharp/CSharpExtensions.cs,b3247464908d9e7a

– Roslyn SyntaxFactory http://source.roslyn.io/#Microsoft.CodeAnalysis.CSharp/Syntax/SyntaxFactory.cs


8 thoughts on “#VS2015 – Delete all comments in a file with #Roslyn

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s