Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code Formatting in Roslyn SDK Preview

Tags:

c#

roslyn

In an earlier version (Roslyn CTP), I was using following code to format my generated code and it was working perfectly fine:

SyntaxNode.Format(FormattingOptions.GetDefaultOptions()).GetFormattedRoot()

With the new Roslyn version it no longer does, so what is the equivalent for the above code in the new version (SDK Preview)?

like image 439
Pratik Mehta Avatar asked May 13 '14 08:05

Pratik Mehta


2 Answers

Roslyn has changed quite a lot since the CTP.

Documentation is now here: https://roslyn.codeplex.com/

Follow the link to https://roslyn.codeplex.com/documentation, click on "Samples and Walkthroughs", then open up the demo solution "FormatSolution - A console application that formats all C# and VB source files in a solution.".

Unfortunately, I don't think its possible to quickly get formatting working any more, as you have to add the code to a new solution.

like image 178
Contango Avatar answered Oct 09 '22 07:10

Contango


You can format SyntaxNodes using the Microsoft.CodeAnalysis.Formatting.Formatter like this (if you have a workspace):

using Microsoft.CodeAnalysis.Formatting;

var formattedResult = Formatter.Format(syntaxNode, workspace);

EDIT: As Jeroen wrote in a comment, if you don't have a workspace and don't need workspace-specific formatting settings, you can just create one:

var workspace = MSBuildWorkspace.Create();
like image 31
andyp Avatar answered Oct 09 '22 06:10

andyp