I'm trying to replace CompilationUnitSyntax of a class using Roslyn.
However, ReplaceNode that I'm using has a different signature than ReplaceNode in Roslyn FAQ and any StackOverflow question that I've looked at. Can anyone point out why is that, and how can I use ReplaceNode that takes old ClassDeclarationSyntax and new ClassDeclarationSyntax as parameters?
I'm looking at September CTP FAQ¹, method:
[FAQ(26)]
public void AddMethodToClass()
particularly the following line:
CompilationUnitSyntax newCompilationUnit =
compilationUnit.ReplaceNode(classDeclaration, newClassDeclaration);
When I'm attempting to build this code, I'm getting an error because ReplaceNode expects different arguments:
'Roslyn.Compilers.CSharp.CompilationUnitSyntax' does not contain a definition for 'ReplaceNode' and the best extension method overload
'Roslyn.Compilers.CSharp.SyntaxExtensions.ReplaceNode<TRoot>(TRoot,
Roslyn.Compilers.CSharp.SyntaxNode,
Roslyn.Compilers.SyntaxRemoveOptions,
System.Func<Roslyn.Compilers.CSharp.SyntaxNode,Roslyn.Compilers.CSharp.SyntaxTriviaList>,
System.Func<Roslyn.Compilers.CSharp.SyntaxNode,Roslyn.Compilers.CSharp.SyntaxTriviaList>)'
¹ I'm fairly sure I'm using the September CTP:
I'm using the FAQ from %userprofile%\Documents\Microsoft Roslyn CTP - September 2012\CSharp\APISampleUnitTestsCS\FAQ.cs
NuGet says that my Roslyn package has version 1.2.20906.2
Immutability means that every time we apply changes to a syntax tree, we’re given an entirely new syntax tree. By default we can’t compare nodes across trees, so what do we do when we want to make multiple changes to a syntax tree? Roslyn gives us four options:
The syntax tree is generated from a script, and I want the result to be a script-based syntax tree too - but for some reason, replacing a node in the tree creates a new syntax tree with changed options: the Kind becomes Regular instead of Script.
One drawback of Roslyn’s immutability is that it can sometimes make it tricky to apply multiple changes to a Document or SyntaxTree. Immutability means that every time we apply changes to a syntax tree, we’re given an entirely new syntax tree.
There are two overloads of ReplaceNode()
(both are extension methods):
public static TRoot ReplaceNode<TRoot, TNode>(
this TRoot root, TNode oldNode, TNode newNode)
where TRoot : CommonSyntaxNode where TNode : CommonSyntaxNode;
in Roslyn.Compilers.CommonSyntaxNodeExtensions
.
public static TRoot ReplaceNode<TRoot>(
this TRoot root, SyntaxNode node, SyntaxRemoveOptions options,
Func<SyntaxNode, SyntaxTriviaList> keepLeadingTrivia = null,
Func<SyntaxNode, SyntaxTriviaList> keepTrailingTrivia = null)
where TRoot : SyntaxNode
in Roslyn.Compilers.CSharp.SyntaxExtensions
.
You want the first one, but the error message talks about the second one, which indicates that you're missing using Roslyn.Compilers;
.
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