Automatically place the ‘System’ directives first when ‘Sorting Usings’ option in Visual Studio

By | January 6, 2015

Sort and Remove the unused namespaces is a standard coding practices.  In the Visual Studio IDE, you can achieve it very easily with the help of  “Organize Usings” options,  or just enable a shortcut key like explained in the Remove and Sort – Namespaces using Shortcut in Visual Studio tip.  In sort, we have three different options for “Organize Using” . Either you can Remove Unused Usings , Sort Usings or we can do it together by selecting “Remove and Sort” .  With the use of “Sort Using”  or “Remove and Sort” options we may face another type of code analysis issue that says ‘System Directives should be place first’. Because standard practices says, we have to keep the System Namespaces first, and when do perform sorting it just do in a alphabetical order.

Most of the time we do this placement / arrangement manually by ourselves. Whereas Visual Studio can take care of this automatically.  From Tools Menu, Navigate to Options –> Text Editor –-> C# –> Advanced.  In the Advance options select the “Place ‘System’ directives first when sorting usings” check box.

Place ‘System’ directives first when sorting usings

Place ‘System’ directives first when sorting usings

 

That’s all. Going forward, whenever you will apply “Sort Usings”, or “Remove and Sort” , Visual Studio will sort the usings as usual, but would also ensure that, all the system directive places in the top in a sorted order.

Here is a quick illustration on how you can use this feature…

Consider you have following set of namespaces included in your code file. They are not sorted, and few of them are unused.

Namespaces

Namespaces

Right Click on the Editor, and either select “Sort Usings” or “Remove and Sort” from the “Organize Usings’ context menu.

Organize Usings

Organize Usings

 

Consider if you had selected “Remove and Sort” and that clean up your usings as follows.  Also, they are now in sorted as well.

Sorted Namespaces

Sorted Namespaces

 

While this is fine, Static Code analysis says, all the system directives should come first.  And, now if you run the stylecop, if you will get bellow warning.

Static Code  Analysis Error

Static Code Analysis Error – “Place ‘System’ directives first when sorting usings’

 

So, either you have to manually move all the system namespaces top of all other namespaces, or enable to the “Place ‘System’ directives first when sorting usings” check box as mentioned earlier.

That will automatically place the System namespaces first.

Sorted Namespaces including System

Automatically Sorted Namespaces including System

 

 

Hope this was usefully.

Thanks.

Abhijit