2

I have a CSharpSyntaxRewriter that adds a new using directive to my file:-

public class AddUsingDirective : CSharpSyntaxRewriter
{
    public override SyntaxNode VisitNamespaceDeclaration(NamespaceDeclarationSyntax node)
    {
        // this adds the using directive inside the namespace not outside
        node = node.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("MyCompany.MyProject.DataAccessLayer.Abstractions"))).NormalizeWhitespace();

        return base.VisitNamespaceDeclaration(node);
    }
}

The problem is that is adds the new using directive inside the namespace but I want to add it to the other existing namespaces above the namespace declaration. Any ideas how I can do this?

1
  • 2
    Once you've got the NamespaceDeclarationSyntax it's too late -- the only thing you can change is the namespace declaration, and you want to change something outside of the namespace declaration. You need to be editing the CompilationUnit, see here Commented Jan 16, 2023 at 11:39

1 Answer 1

0
public override SyntaxNode VisitCompilationUnit(CompilationUnitSyntax node)
{
    // this adds the using directive inside the namespace not outside
    node = node.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("MyCompany.MyProject.DataAccessLayer.Abstractions"))).NormalizeWhitespace();

    return base.VisitNamespaceDeclaration(node);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.