Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Roslyn how do I update the class using directives?

Tags:

c#

roslyn

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

like image 224
shenku Avatar asked Jun 26 '13 05:06

shenku


1 Answers

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.

like image 162
nemesv Avatar answered Nov 15 '22 15:11

nemesv