Remove unnecessary using directives in C#


[using directives]

The top of a C# code file usually 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?

This post’s picture shows the code in a new Windows Form created in Visual Studio 2017. 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 last of these, System.Windows.Forms, is necessary. Depending on what the program does, the others may not be.

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 actually 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. In Visual Studio 2017, using directives that are not needed are grayed out, as you can see in the picture at the top of the post. In older versions of Visual Studio, you can comment out the directives one at a time and see which ones cause errors.

An easier method is to let the code editor remove unnecessary usings for you. In Visual Studio 2017, right-click in the code editor and select Remove and Sort Usings. In older versions of Visual Studio, right-click and dig around to find the right menu item.


Follow me on Twitter   RSS feed   Donate




This entry was posted in coding, performance and tagged , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *