Home > Refactorings > Refactorings – Optimize Namespace References

Refactorings – Optimize Namespace References

April 15th, 2011

The Optimize Namespace References refactoring removes namespace references (usings (in C#) or Imports (in VB)) that are not needed in the active source file, either because they were added automatically and not used, or because the code that did require them has been removed or relocated. Also, it can automatically sort used references after refactoring is performed: alphabetically, by length or not sort. An additional sorting option is to move all System references at the top of the list (file). The refactoring improves code readability.

On the other hand, Visual Studio already has a similar built-in feature called Organize Using Statements, available via right-clicking the context menu in the code editor. The “Organize Usings” feature provides a way to sort and remove using and alias declarations.

Let’s compare these two features: Refactor! Optimize Namespace References and Visual Studio Organize Usings:

VS Organize Usings

Optimize Namespace References

References sorting

Sorting methods Alphabetically, Place ‘System’ directives first when sorting usings Alphabetically, By Length, Move System References at the top
Aliases support

(Partially – unused aliases are removed, but not sorted)
Option to leave favorite references


Languages support C# (For VB support you may install Productivity Power Tools) C#, VB, C++
Visual Studio support VS2008 and up VS2005 and up
Works across solution

(Macros can be written as a work-around)

(DXCore plug-in can be written as a work-around)

(*) This option is available since release 11.1.

The Optimize Namespace References refactoring is shipped in Refactor! Pro. It has a preview hint as most of other refactorings, so you are able to see what references are going to be removed:

Refactor! Optimize Namespace References refactoring

The sorting method and the list of references to keep is configurable on the Optimize Namespace Reference options page (in the “Editor | Refactoring” category) in the IDE Tools Options Dialog:

Refactor! Optimize Namespace References options page

To sort namespace references without optimizing them, you are able to use the stand-alone Sort Namespace References refactoring, which allows you to choose the sorting algorithm right in the Popup menu instead of options page.

Products: Refactor! Pro
Versions: 11.1 and up
VS IDEs: any
Updated: Jun/30/2011
ID: R023

Similar Posts: