Question

I try to add a method to the class using Roslyn.
I parse .cs file and get the decidered class.

SyntaxTree tree = SyntaxTree.ParseFile(Path);
CompilationUnitSyntax root = (CompilationUnitSyntax)tree.GetRoot();
MemberDeclarationSyntax firstMember = root.Members[0];
TypeDeclarationSyntax lClassDeclarationSyntax = (TypeDeclarationSyntax)NamespaceDeclaration.Members[1];

Then i create an instance of the type MemberDeclaration

MethodDeclarationSyntax lMethodDeclarationSyntax= Syntax.MethodDeclaration(
Syntax.List<AttributeListSyntax>(),
Syntax.TokenList(),
Syntax.IdentifierName("MemoryStream"),
null,
Syntax.Identifier("Serialize"),
null,
Syntax.ParameterList(),
Syntax.List<TypeParameterConstraintClauseSyntax>(),
Syntax.Block(lList));

where lList is the body of method. Then i try to add this instance to the class

lClassDeclarationSyntax.Members.Add(lMethodDeclarationSyntax);

but nothing in response. How i can do this?

Was it helpful?

Solution

Roslyn syntax trees are immutable, so the Add method returns a new SyntaxList, it doesn't update it in place. You probably want something like

var newClass = lClassDeclarationSyntax
.WithMembers(lClassDeclarationSyntax.Members.Add(lMethodDeclarationSyntax));

This is something we are working on making clearer in the method names.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top