shenku
shenku

Reputation: 12458

Using Roslyn how do I update the class using directives?

Just discovering Roslyn, so please be patient.

I would like to update the using directives at the top of my class to include an additional statment, for example:

using System;

public class Foo {

}

Should become:

using System;
using Custom.Bar;

public class Foo {

}

I see that I can override SyntaxRewriter and I have done this to address method level code, but I can't see an override that might give me access to these using directives?

Thanks.

Edit:

I have found this property, but I don't know how to modify it.

var tree = document.GetSyntaxTree().GetRoot() as SyntaxNode;

var compilationUnitSyntax = (CompilationUnitSyntax) (tree);

if (compilationUnitSyntax != null)
      compilationUnitSyntax.Usings.Add();

Unfortunately UsingDirectiveSyntax is internal so how can I add one! :D

Upvotes: 10

Views: 3758

Answers (1)

nemesv
nemesv

Reputation: 139798

To create SyntaxNodes you must use the Syntax class factory methods in your case the Syntax.UsingDirective method.

And you can add a new using with the AddUsings method something like

if (compilationUnitSyntax != null)
{
    var name = Syntax.QualifiedName(Syntax.IdentifierName("Custom"),
                                    Syntax.IdentifierName("Bar"));
    compilationUnitSyntax = compilationUnitSyntax
        .AddUsings(Syntax.UsingDirective(name).NormalizeWhitespace());
}

Note: because of the immutability of the CompilationUnitSyntax you need to reassign your compilationUnitSyntax variable with the result of the AddUsings call.

Upvotes: 18

Related Questions