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.
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
}
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