Skip to content

Document the best practice for getting text from a syntax in source generators #6017

@Neme12

Description

@Neme12

When writing source generators, many users choose to generate the code using the syntax APIs because they find this approach useful for their scenario, even though AddSource only takes a SourceText, not syntax nodes. To get the SourceText from the syntax, the best way is to use AddSource(syntaxNode.GetText(Encoding.UTF8)) - this is more efficient than using syntaxNode.ToString() or syntaxNode.ToFullString() (which is the naive approach that most people would use) because it avoids the string allocation, which could be arbitrarily large. It would be helpful to have this documented in some of the source generator walkthroughs as a recommended/best practice for getting the text from a syntax in case the users choose to generate the code using the syntax APIs, to guide users to do the right thing.

Extracted from dotnet/roslyn#49082 (comment)

The best way to get a SourceText from a CompilationUnit, or any SyntaxNode in general, is to use syntaxNode.GetText(Encoding.UTF8) - that way, no huge string should be allocated.

IMO, it would be a good idea to mention this somewhere in the docs for source generators, so that people do the right thing, as opposed to calling syntaxNode.ToString().

...

Also, getting a SourceText from the syntax is already easy to do in a pretty good way, by using syntaxNode.GetText(Encoding.UTF8). This just needs to be documented so that source generator authors know that this is the recommended practice for getting the text from a syntax, in case they're using the syntax APIs to generate the source.

@jasonmalinowski @chsienki @AArnott

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions