0

I want to add a <T> after DeserializeObject like JsonConvert.DeserializeObject<T>(json) Below is how I'm trying to achieve it

var desiToken = node.DescendantTokens().Where(x => x.Text == "DeserializeObject").FirstOrDefault();
List<SyntaxToken> NewTokenList = new List<SyntaxToken>()
        {
            desiToken
        };

var tokenList = SyntaxFactory.TokenList(NewTokenList);
var newNode =node.InsertTokensAfter(tokenList[0],new[]{SyntaxFactory.ParseToken("<"),SyntaxFactory.ParseToken("T"),SyntaxFactory.ParseToken(">")} ); 
//"node" is of type MethodDeclarationSyntax

But this doesn't seem to work, Nothing is happening, newNode doesn't have the modified code.

Also the reason I'm creating SyntaxTokenList, after digging a lot I found that the SyntaxToken has to be part of a SyntaxTokenList, otherwise it throws exception

Below is another way I tried After I realized that Span information is starting from zero

var xyz = SyntaxTokenList.Create(desiToken);

Even though now the span information is coming correctly, It throws the exception "System.InvalidOperationException:

'The item specified is not the element of a list.'

like before.

I couldn't find any blog/video related to this, can anyone show me the correct way

S G T
  • 1
  • 1

1 Answers1

0

The Roslyn syntax trees are immutable; InsertTokensAfter returns the new node with the change you've requested.

Jason Malinowski
  • 18,148
  • 1
  • 38
  • 55