0

In CodeFixProvider I need to remove wrapping if-condition (for example):

if (temp == null)
{
    temp = new Temp();  
}

and I want to leave only adjusted inner expression:

// I want to change the inner expression as well
temp = anotherTemp()

As soon as I attempt to replace nodes of 'if-block' with line-line statement, 'unable to cast' exception is thrown. Do you know proper way to do it?

svick
  • 236,525
  • 50
  • 385
  • 514
Divisadero
  • 895
  • 5
  • 18
  • 1
    Show us your code and the exact error. – SLaks Mar 18 '16 at 14:45
  • I have posted my solution as an answer, but 'unable to cast' exception will emerge anytime you will replace nodes of different kinds. It makes sense actually, only i do not know how to procede. But as @Jeroen Vannevel mentioned, DocumentEditor should be the answer. I remember that I had the same problem with it, but maybe I made a mistake somewhere. Iwill check it and write here if I find a solution – Divisadero Mar 18 '16 at 15:00

1 Answers1

0

Only solution I have found out is to insert adjusted inner expression before if-condition block and remove that block afterwards. To do that successfuly, you have to track parent block node, otherwise it wont work.

  IfStatementSyntax originalIfStatement = parentIfStatement;
  root = root.TrackNodes(originalParentIfStatement);
  parentIfStatement = root.GetCurrentNode(originalParentIfStatement);
  root = root.InsertNodesBefore(parentIfStatement, new[] { SyntaxFactory.ExpressionStatement(newExpression) });
  parentIfStatement = root.GetCurrentNode(originalParentIfStatement);
  root = root.RemoveNode(parentIfStatement, SyntaxRemoveOptions.KeepNoTrivia);

If anybodody see any mistake, please, tell me.

Divisadero
  • 895
  • 5
  • 18