Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't add member to the Class programmatically using Roslyn

Tags:

c#

roslyn

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?

like image 373
Imorian Avatar asked Feb 11 '14 14:02

Imorian


1 Answers

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.

like image 91
Kevin Pilch Avatar answered Oct 05 '22 22:10

Kevin Pilch