mohsen
mohsen

Reputation: 1806

How do I modify class declaration syntax correctly with Roslyn?

I have a method below to modify class declaration syntax. I added two StatementSyntax attributes to all methods in the class, and then I will save that class to my solution. Everything is good, but the method ReplaceNode only works for the first method, ListOfMethod. Which part of my method is incorrect?

private ClassDeclarationSyntax GetNewClass(ClassDeclarationSyntax c)
{
    List<MethodDeclarationSyntax>  ListOfMethod = lom(c);
    foreach (var OldMethod in ListOfMethod )
    {
        MethodDeclarationSyntax NewMethod = GetNewMethod (OldMethod);
        c = c.ReplaceNode(OldMethod,NewMethod);
    }
    return c;
}

Upvotes: 0

Views: 1237

Answers (2)

Tamas
Tamas

Reputation: 6420

In Roslyn, most of the data structures are immutable, so when you call a modifying method on something, then that operation will return a new modified object, and not perform the modification in place.

So in your case, you collect all the methods that interest you from a given ClassDeclarationSyntax. When you call the ReplaceNode, that returns a new class declaration. This new class declaration won't contain any of your previously found methods, because it's a new class declaration instance.

One option is to do the change in a single call with ReplaceNodes, and in your case this seems to be the approach to follow.

Another option is to try to mark the methods with some permanent marking that is not lost during tree modification. To do this you can add annotations to the nodes with WithAdditionalAnnotations(), and then you can find in the tree a given node with a given annotation.

Upvotes: 5

mohsen
mohsen

Reputation: 1806

I changed the method like below .every time I use the method ReplaceNode the new classdeclarationsyntax will be created then I must get next MethodDeclarationSyntax from this new one

into Count =c.Members.OfType <MethodDeclarationSyntax>().Count();
for  (int i=0;i <Count; i++)
{
    List <MethodDeclarationSyntax > l=c.Members.OfType <MethodDeclarationSyntax>().ToList();
    MethodDeclarationSyntax NewMethod=GetNewMethod (l [i]);
    c=c.ReplaceNode(l [i],NewMethod);
}

Upvotes: 0

Related Questions