Home > Back-end >  unnesting namespace c# visual studio
unnesting namespace c# visual studio

Time:12-20

I have a nested namepace DO as a part of a big project.

namespace IDAL
{
    namespace DO
    {
        public struct MyStruct
        {
            // Code
        }
    }
}

I need to change the name of the IDAL namespace to DalApi and the nested namespace IDAL.DO toDO.

The first part was easy enough using the Visual Studio Rename option.

I ran into more difficulty with the second part. I can't use the Rename option to extract the namespace and make it a non nested namespace.

I tried just removing the outer namespace like this,

    namespace DO
    {
        public struct MyStruct
        {
            // Code
        }
    }

but the I needed to start fixing up all of the times that the namespace was referenced (i.e. IDAL.DO.WeightCategory - where WeightCategory is an enum needs to be changed to DO.WeightCategory just to give one example). While that seemed that it would work, it seemed that it was a lot of difficult work which probably had an easier solution.

I tried to use the Ctrl H search and replace feature to try and replace all instances where this happened but it didn't seem to solve the problem (it was set to replace for entire solution).

Is there a Visual Studio 2019 tool where I can easily change (refactor) a nested namespace to a non nested namespace?

CodePudding user response:

From Visual Studio, while having the cursor on MyStruct, do a CTRL . on it:

enter image description here

And then just click on "Move to namespace..." and write whichever namespace you want, and VS will take care of the rest:

enter image description here

CodePudding user response:

Do you also need the effective namespace IDAL.DO to change? If not you could simply swap to the fully qualified namespace like so:

namespace IDAL.DO
{
    public struct MyStruct
    {
        // Code
    }
}

If you do want to change the full namespace to become simply DO then refactoring tools are indeed what you'll need to use. The following links should get you started in that regard:

https://dev.to/gopkumr/adjust-namespaces-automatically-visual-studio-2019-1f0b https://docs.microsoft.com/en-us/visualstudio/ide/refactoring-in-visual-studio?view=vs-2022 https://docs.microsoft.com/en-us/visualstudio/ide/reference/extract-method?view=vs-2022 https://docs.microsoft.com/en-us/visualstudio/ide/reference/move-type-to-matching-file?view=vs-2022

  • Related