Cleaning up ‘using’ directives


A suggestion arrived in email, and here is my response.  (None of this is on the feature list for Whidbey, it’s just ideas.)


 


1. Fully qualify (all names / all names in namespace X / all instances of type Y / the instance under my cursor), removing a using directive if possible.


 


1a. Add ‘global::‘ when doing this.


 


2. Least-qualify (one of the above) by removing namespace from the name and adding a using directive.


 


3. Partially-qualify names from stuff within this project.  That means writing like this:


 


using System.Foo;


using System.Bar;


 


namespace Microsoft.Product.Feature.ComponentA


{


     class C {}   


}


 


namespace Microsoft.Product.Feature.ComponentB


{


     class D


     {


          ComponentA.C x;


     }   


}


 


4. Find all unused using directives (one you can remove without changing the meaning of the code).  A little tricky if you use #if, so avoid it.!


 


5. Sort using directives alphabetically.  Insert a blank line to separate different top-level namespaces.

Comments (8)

  1. Jerry Pisk says:

    I personally like Java’s take better, when you cna specify types to be imported, not whole namespaces. Looks like Microsoft once again decided to go with developers who do not want to be bothered with listing the actual types they use (even though Java allows you to import the whole namespace as well). And of course the "Organize Imports" feature in Java IDEs makes life a lot easier, not sure if VS has anything like that.

  2. All sound good to me.

  3. Theo Yaung says:

    Jerry, you can import single types (at least in C#) by using type aliasing:

    using WindowsIdentity = System.Security.Principal.WindowsIdentity;

    So you’re not completely at loss if you were to only want a couple types from that namespace… it’s just that for whole namespaces, you don’t have to add the ".*" :-)

  4. Dave Thomas says:

    Is there currently anyway to remove unused using statements?

  5. Scott Hodson says:

    The Xtreme Simplicity Refactoring plug-in for VS.NET has a "Tidy Imports" feature that will clean up unused imports.

  6. jaybaz [MS] says:

    Thanks, Scott. Do you use it? A lot? Does it meet your needs?