I needed to do a refactor that broke a namespace into multiple namespaces. Their may be some other way to do this in Visual Studio. The easiest way I thought of was finding & replacing the old namespace with the new namespaces. This meant I would be adding namespaces to files they weren't used in. Not a big deal, but something I prefer to avoid.
Fortunately for me, Visual Studio added a sweet new clean up feature in version 15.8. It even works on the free Community version.
Go to Tools > Options > Text Editor > C# > Code Style > Formatting.
It has an experimental Format Document Settings where you can have Visual Studio clean up your code. Two of the options are to "Remove unnecessary usings" and "Sort usings".
Check these two and you're good to go! No need for an extension or ReSharper to do this anymore.
Update: For Visual Studio 2019, it appears this will be living in a different location named "Configure Code Cleanup". You can open up the configuration these ways:
- The easiest way to find anything in Visual Studio is click Ctrl+Q or click the "Search Visual Studio" toolbar & type it in.
- In the menu go to Analyze > Code Cleanup > Configure Code Cleanup.
Once you've configured code cleanup, you need to run it. Here are your options:
- The first profile you've setup you can run with Ctrl+K, Ctrl+E.
- On the bottom (leftish) of your screen there is a tiny broom icon. Click that.
- In the menu go to Analyze > Code Cleanup. Then select the cleanup profile you want to run.
- You can run code cleanup on save with Mads Kristensen's extension.