CodeGeneration. Problems calling ReplaceTrivia method on some comments. The issue arises when attempting to replace all comments in a method using the ReplaceTrivia method from the Roslyn API. Although the intention is to change each comment to a new format, only the first comment gets replaced correctly.
Source code
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
...
public string Transform(string methodBody)
{
var tree = CSharpSyntaxTree.ParseText(methodBody);
var root = tree.GetRoot();
var comments = root.DescendantTrivia()
.Where(trivia => trivia.IsKind(SyntaxKind.SingleLineCommentTrivia))
.ToList();
var commentGenerator = new MethodCommentGenerator();
foreach (var comment in comments)
{
var newCommentText = commentGenerator.GenerateCommentName(comments.IndexOf(comment));
var newTrivia = SyntaxFactory.Comment(newCommentText);
root = root.ReplaceTrivia(comment, newTrivia);
}
return root.ToFullString();
}
public class MethodCommentGenerator
{
public string GenerateCommentName(int order) => $"// comment{++order}";
}
I want to change all comments in the method to my own. For some reason, only the first one changes. For example,
public string TestFunc(string key, string value)
{
// set val1
var val1 = key;
// set val2
var val2 = value;
// return result
return $"({val1}{ val2})";
}
turns into
public string TestFunc(string key, string value)
{
// comment1
var val1 = key;
// set val2
var val2 = value;
// return result
return $"({val1}{ val2})";
}
I want it to be
public string TestFunc(string key, string value)
{
// comment1
var val1 = key;
// comment2
var val2 = value;
// comment3
return $"({val1}{ val2})";
}