Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting Code Between Region Trivia With Roslyn

Tags:

c#

roslyn

How can I insert a variable declaration after a region directive in Roslyn? I'd like to be able to do something like going from this:

class MyClass 
{
    #region myRegion
    #endregion
}

to this:

class MyClass 
{
    #region myRegion
    private const string myData = "somedata";
    #endregion 
}

I can't seem to find any examples that deal with trivia in this manner.

like image 596
Andr0s Avatar asked May 10 '26 12:05

Andr0s


1 Answers

That's quite tricky to do with a CSharpSyntaxRewriter, because both the #region <name> and #endregion end up in the same SyntaxTriviaList, which you'd have to split out and figure out what to create instead. The simplest way to not bother with all the intricacies, is to create the corresponding TextChange and modify the SourceText.

var tree = SyntaxFactory.ParseSyntaxTree(
@"class MyClass
{
    #region myRegion
    #endregion
}");

// get the region trivia
var region = tree.GetRoot()
    .DescendantNodes(descendIntoTrivia: true)
    .OfType<RegionDirectiveTriviaSyntax>()
    .Single();

// modify the source text
tree = tree.WithChangedText(
    tree.GetText().WithChanges(
        new TextChange(
            region.GetLocation().SourceSpan,
            region.ToFullString() + "private const string myData = \"somedata\";")));

After that, tree is:

class MyClass 
{
    #region myRegion
private const string myData = "somedata";
    #endregion
}
like image 148
m0sa Avatar answered May 13 '26 20:05

m0sa