Adding a namespace reference to a file

How can I check if a namespace is already in a C# source file and if it's not there how do I add it?

Is there a sample for this?


ta

Ollie

8 comments
Comment actions Permalink

Hi Ollie. Do you mean declaring a namespace ("namespace Foo {") or using a namespace ("using Foo;")?

0
Comment actions Permalink

adding a new using statement ("using Foo;")


ta

Ollie

0
Comment actions Permalink

I've found this previous question and answer on the forums - http://devnet.jetbrains.com/message/5218112#5218112

0
Comment actions Permalink

How do I add the 'using namespace' to nested scope - inside the namsepace for the file?


ta

Ollie

0
Comment actions Permalink
I don't think you can, using this method. I think UsingUtil will place it where the settings for the code say it should go - if you've set that up to be inside, it should be inside.
0
Comment actions Permalink

I managed to achieve it with the correct nesting of the 'using statement' - failing to find any nested instances it stick it at top of the file:

private static void EnsureNamespaceExists(ICSharpFile file, CSharpElementFactory factory)
{
    var namespaceExists = file.NamespaceDeclarationNodes.Any(n => n.Imports.Any(d => d.ImportedSymbolName.QualifiedName == AsObservableNamespace));
    if (!namespaceExists)
    {
        var directive = factory.CreateUsingDirective(AsObservableNamespace);
                
                var namespaceNode = file.NamespaceDeclarationNodes.FirstOrDefault();
        if (namespaceNode != null)
        {
           UsingUtil.AddImportTo(namespaceNode, directive);
        }
        else
        {
           UsingUtil.AddImportTo(file, directive);
        }
    }
}



ta

Ollie
0
Comment actions Permalink
Cool. Are you R# settings set to put using statements inside the namespace declaration? If so, it kinda sounds like a bug that by default ReSharper would add them at the top of the file. I would expect it to honour your settings when adding.
0
Comment actions Permalink

yeah my settings are for nested namespaces - i'll check later and see if it's doing it as expected.


ta

Ollie

0

Please sign in to leave a comment.