Visual Studio 2008 Tip: Resolving Namespaces and Removing Unused Using Statements

Visual Studio 2008 Tip: Resolving Namespaces and Removing Unused Using Statements

by David Hayden, Microsoft MVP C#

 

I had the absolute joy of hanging out at the Tampa .NET Developer Group Meeting last night. Here is a tip I mentioned briefly at the meeting around resolving and optmizing namespaces.

I know a lot of us are hardcore ReSharper users and can do all kinds of jedi-like moves in the Visual Studio 2008 IDE. However, get us without ReSharper at times and we just stare at the keyboard in bewilderment wondering why namespaces aren't resolving, usings are being optimized, and refactorings are not taking place at blinding speeds, etc.

It turns out, Visual Studio 2008 actually has good support for resolving namespaces and optmizing using statements that can get you the functionality if you are not using ReSharper.

 

Resolving Namespaces

When you are writing code and Visual Studio places a small red notification rectangle at the end of the class,

 

Visual Studio 2008 Namespace

 

Pressing Ctrl + . will bring up a context-sensitive menu that allows you to add a using statement or optionally fully qualify the path to the class.

 

Visual Studio 2008 Add Using Statement

 

Clicking the Enter Key will automatically add using System.Collections.Generic; with the other using statements, requiring no touch of the mouse.

This also works with attributes as well. Adding an attribute that needs a using statement to qualify its namespace will cause the same red notification rectangle to appear:

 

Visual Studio 2008 Add Using Statement for Attributes

 

and pressing Ctrl + . will allow you to add the using statement, etc.

 

Visual Studio 2008 Add Using Statement for Attributes

 

Optimizing, Removing, and Sorting Unused Using Statements

The other nice thing that ReSharper does is remove unused using statements using Ctrl+Alt+O.

We can get that using Visual Studio 2008, because you may have noticed the cool context-sensitive Organize Usings Option:

 

Visual Studio 2008 Organize Your Usings

 

Very, very cool, but this needs to have a shortcut because we will be using it often. I want to use the familar Ctrl+Alt+O shortcut that I get from ReSharper ( you can choose your own ) so I need to map the shortcut to the Edit.RemoveAndSort Command in the keyboard options:

 

Visual Studio 2008 Shortcut

 

Now when I type Ctrl+Alt+O in the code editor it will remove all unused using statements in the current file as well as sort those using statements that are being used.

Very cool! Hope this helps.

by David Hayden, Microsoft MVP C#

 

posted on Tuesday, January 29, 2008 11:55 AM

My Links

Post Categories

Article Categories

Archives

Loose-Leaf Tea