using KEYWORD IN C#
There are two ways of using the
using keyword in C#:
using KEYWORD AS A STATEMENT
MSDN says the
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.
Another use of using is to create aliases. An excellent discussion on this topic can be found in this Stackoverflow thread.
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
This menu item has three sub-items:
- Remove Unused Usings
- Sort Usings
- Remove and Sort
Remove Unused Usings:
This option simply removes unused using directives. The end result would be like:
This option only sorts the using directives alphabetically. It does nothing else. Also, the sort can not be done in reverse alphabetical order:
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:
This keeps the class file clean and some unnecessary lines of code can be reduced (if that sort of thing appeals to you).