Andry Andry - 12 days ago 8
C# Question

Incorrect syntax is generated when creating a UsingDirective from factory in Roslyn

I am using Roslyn in order to generate a tree from another one. So we are dealing with AST transformation. I am using

SyntaxFactory
in order to generate nodes.

In the specific case I want to create a u
using
directive that should look like this:

using MyNamespace.SubNamespace;


So I do:

var usingDirective = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("MyNamespace.SubNamespace"));
var newNode = mynode.AddUsings(new[] { usingDirective });


But if I inspect the final tree
newNode
which is generated (the string source code generated by simply calling
newNode.ToString()
), I see that my directive has been added like this:

usingMyNamespace.SubNamespace;


I can see the same thing if I just do:
usingDirective.ToString()
. It seems very wrong, a space is needed and that should trigger a syntax error. What is going on?

Answer

Add this to fix the problem:

SyntaxFactory.UsingDirective(
    SyntaxFactory.ParseName("MyNamespace.SubNamespace")).NormalizeWhitespace();