icsharpcode / NRefactory

NRefactory - Refactoring Your C# Code
684 stars 264 forks source link

Add namespace to every typedeclaration #354

Open Mittchel opened 11 years ago

Mittchel commented 11 years ago

Hey there,

For a project I'm working on I would like to visit every type declaration and add them into a different namespace.

I'm using NRefactory with the visitor pattern in order to achieve this. I'm having trouble to place the typeDeclaration into a new namespace.. I've tried the following code:

typeDeclaration.Parent.InsertChildBefore(typeDeclaration, newNamespace, new Role("customNamespace"));

But I'm not sure if I'm in the right direction. Is anyone able to assist me with this particular problem?

What I basically want is:

namespace customnamespace { class C { } }

Regards, Mittchel

arashthk commented 10 years ago

Hey @Mittchel I get your point, but to be honest your code is a bit twisted ! How about this :

var namespacesCollection = syntaxTree.Descendants
    .OfType<TypeDeclaration>()
    .Select(declaration => new NamespaceDeclaration
    {
        Name = "Ns." + declaration.Name,
        Members =
        {
            declaration.Clone()
        }
    });

Or you can simply put it in a type declaration visitor. BTW, Make sure that you're using latest version of NRefactory. There's been some changes in namespaces.