Visual Studio: Is there a "move class to different namespace" refactoring?
Solution 1:
Visual Studio 2019 provides at least 2 built-in options:
'Move to namespace...' refactoring can be triggered on any class, and VS will prompt for the target namespace.
'Change namespace to...' refactoring is provided for when the current file namespace doesn't match with the folder structure.
This can be used to move individual classes to a different namespace by:
- creating the desired folder structure
- moving the file
- applying the mentioned refactoring (CTRL+. with the cursor over the namespace)
These operation ensures that all references are updated accordingly.
Solution 2:
Visual Studio 2010 has the possibility to rename a namespace. Place the cursor over the namespace name and press F2. Or simply rename it in the code and press Shift+Alt+F10, Enter after seeing the red squiggle appear.
Reharper can also rename namespaces. Quote:
The Rename Namespace refactoring allows users to rename a specific namespace and automatically correct all references to the namespace in the code. The following usages are renamed:
- Namespace statements
- Using directives
- Qualified names of types
Solution 3:
As mentioned in the comments, this answer is now outdated. Please see the up-to-date answer below
Resharper is the only tool I am aware of what has this ability. There is also a lot of other functionality that it has that is missing in CodeRush and Refactor!
Solution 4:
This answer applies to at least Visual Studio 2013 and 2015 with no resharper required
- Move class files to new folder
- Open 'Find and replace'
- Select 'Replace in Files'
- Type the original namespace definition in the 'Find what' field eg.
MyCorp.AppStuff.Api
- Type the new namespace definition in the 'Replace with' field eg.
MyCorp.AppStuff.Api.Extensions
- Select the new folder using the 'Look in' field's browse button ..., or type the folder path
- Press the Replace All button