To be more specific: Microsoft.CodeAnalysis.Editing.SyntaxGenerator and Microsoft.CodeAnalysis.CSharp.SyntaxFactory.
1) My understanding is that they are both part of Roslyn, and both used for generating code, is that correct? If yes, are there others in that category?
2) Is one better and/or newer than the other? I only suspect that because I found this.
Each SyntaxFactory (there's one for VB and one for C#) is tightly coupled to its language. In a sense the SyntaxFactory is a "lower level" API which you can use to create syntax trees. You can control every syntax node, token and trivia in your tree when using a SyntaxFactory. This comes at a cost: It's harder to read and understand source code that uses the SyntaxFactory because it's very verbose.
The SyntaxGenerator provides a language agnostic API which can be used to create pieces of either C# or VB .NET syntax. It provides an API that is easier to use and less verbose than the SyntaxFactory. Note that to create a SyntaxGenerator we need either a Document, Project, or Workspace.
If you read through the implementations of the SyntaxGenerator you'll see that they are using the SyntaxFactory under the hood.
We can compare the two APIs when generating the following code:
void Method()
{
}
var method = SyntaxFactory.MethodDeclaration(
SyntaxFactory.PredefinedType(
SyntaxFactory.Token(SyntaxKind.VoidKeyword)),
SyntaxFactory.Identifier("Method"))
.WithBody(
SyntaxFactory.Block()))))
SyntaxGenerator generator = SyntaxGenerator.GetGenerator(...); //We need a Document, Project or Workspace
var method = generator.MethodDeclaration("Method");
The generator is just a cleaner way to build up syntax trees.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With