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.
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.
Right Click on the Editor, and either select “Sort Usings” or “Remove and Sort” from the “Organize Usings’ context menu.
Consider if you had selected “Remove and Sort” and that clean up your usings as follows. Also, they are now in sorted as well.
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.
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.
Hope this was usefully.
Thanks.
Abhijit