We are trying to figure out how to generate code with Roslyn. I'm not talking about something like CSharpSyntaxTree.ParseText , which will take several lines and convert them to AST. Instead, I would like to somehow build my model (pseudocode):
- Create
file as compilation unit - Add
MyClass class to file - Add
DoSomething Method to MyClass - Install the
DoSomething body in the same way as System.Linq.Expressions
We recently discovered Microsoft.CodeAnalysis.CSharp.SyntaxFactory , and that seemed promising. However, obviously, we must add the little things ourselves.
After creating a tree with SyntaxFactory.CompilationUnit() and adding some elements back and forth, the output of ToFullString() is just a bunch of text that is neither readable nor compiled (like no braces). Did we miss something while creating text from the model?
EDIT:
When using workspaces, you can set parameters that affect the behavior in the form of spaces:
public string Generate (CompilationNode rootNode) { var cw = new CustomWorkspace(); cw.Options.WithChangedOption (CSharpFormattingOptions.IndentBraces, true); var formattedCode = Formatter.Format (CreateFile(rootNode), cw); return formattedCode.ToFullString(); }
This already gives the best result. Can someone confirm this as a good solution or is it more likely a hack?
One problem remains. We want to create an auto-property, we are currently using SF.AccessorDeclaration , but it skips the semicolon when converting to a full string.
c # roslyn
Matthias
source share