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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With