The USING keyword in C#: How to clean unnecessary using directives in Visual Studio

using KEYWORD IN C#

There are two ways of using the using keyword in C#:

  1. As a statement
  2. As a directive

using KEYWORD AS A STATEMENT

MSDN says the using keyword

Provides a convenient syntax that ensures the correct use of IDisposable objects.

This is also a way of saying that this is the standard way of releasing unmanaged resources. The following is an example of its usage:

using(StreamWriter grepLog = new StreamWriter(fileName, true))  
{  
// …log code here  
}

using KEYWORD AS A DIRECTIVE

This is the most common usage of the using keyword. The following example shows how **using **keyword is used to access types in a namespace. This practice of using the **using **directives to access types in a namespace allows the developer to avoid fully qualifying the type. This save a lot of time and typing.

using System;
using System.Text;

Another use of using is to create aliases. An excellent discussion on this topic can be found in this Stackoverflow thread.

CLEANING using DIRECTIVES

**

There are many reasons why your .cs file may end up having more using directives than necessary. There is a very quick way to clean and organize using directives in Visual Studio. Just right-click on the text editor. The context menu pops up and the second option in the menu is Organize Usings.

This menu item has three sub-items:

  1. Remove Unused Usings
  2. Sort Usings
  3. Remove and Sort

image

Remove Unused Usings:

This option simply removes unused using directives. The end result would be like:

image

Sort Usings:

This option only sorts the using directives alphabetically. It does nothing else. Also, the sort can not be done in reverse alphabetical order:

image

Remove and Sort Usings:

This option removes all unused using directives and sorts the list too. This sorting is also done alphabetically and no reverse alphabetical sorting option is available:

image

This keeps the class file clean and some unnecessary lines of code can be reduced (if that sort of thing appeals to you).