BLOG.CSHARPHELPER.COM: Remove unnecessary "using" directives in C#
Remove unnecessary "using" directives in C#
The top of a C# code file often includes series of "using" directives to tell Visual Studio which namespaces are used by the code. When you first create a project, the code files include lots of using directives that might be helpful, but what if you don't use those namespaces?
The picture above shows a new C# form's code created in Visual Studio 2012. It includes using directives for these namespaces:
System
System.Collections.Generic
System.ComponentModel
System.Data
System.Drawing
System.Linq
System.Text
System.Threading.Tasks
System.Windows.Forms
The first and last of these, System and System.Windows.Forms, are required for a Windows Forms application. Depending on what the program does, the others may be unnecessary.
So does leaving unnecessary using directives in a program hurt you? Yes and no.
When you compile the application, only the libraries that are actually used are included in the compiled result. That means leaving extra using directives in the code doesn't make the final result any larger or slower.
However, when you build the application, the compiler must resolve all of the symbols in the code. If the compiler encounters a symbol such as Pen, it first tries to find a definition for Pen in the local code. If it doesn't find one, it starts looking through the namespaces included by using directives. If those directives include a lot of namespaces that the program doesn't use, the compiler may be digging through a lot of material that couldn't possibly help, and that may slow things down a bit.
So removing unnecessary using directives can reduce compilation time. You can see which directives are necessary by commenting them out one at a time and seeing which ones cause errors.
An easier method is to right-click in the code editor, open the Organize Usings submenu, and select Remove Unused Usings. If you like, you can also select Sort Usings to make the code editor place the using directives in sorted order. Or if you want to do both of these things, select the Remove and Sort command.
Comments