Overview of Using Keyword in C#

There are two ways to use the using keyword in C#. One is as a directive and the other is as a statement. Let's explain!
 
1. using Directive

Generally we use the using keyword to add namespaces in code-behind and class files. Then it makes available all the classes, interfaces and abstract classes and
their methods and properties in the current page. Adding a namespace can be done in the following two ways:
 
A. To allow the normal use of types in a namespace:
  1. using System.IO;  
  2. using System.Text;  
B. To create an alias for a namespace or a type. This is called a using alias directive. 
  1. using MyProject = TruckingApp.Services;  
We can use the namespace alias as in the following:
  1. MyProject.Truck newObj = new MyProject.Truck();  
This one (option B) is very useful when the same class/abstract/interface is present in multiple namespaces.

Let's say the Truck class is present in TruckingApp1, TruckingApp2 and TruckingApp3. Then it is difficult to call the Truck class of namespace2.

Here the alias directive gives an elegant syntax to use the Truck class.
 
Code
  1. using namespace1 = TruckingApp1.Services;  
  2. using namespace2 = TruckingApp2.Services;  
  3. using namespace3 = TruckingApp3.Services;  
  4.    
  5. namespace2.Truck newObj = new namespace2.Truck();  
Now the code looks more elegant and easy to understand. Except this way you can also access the Truck class using namespace directly as in the following:
  1. TruckingApp.Services2.Truck newObj = new TruckingApp.Services2.Truck();  
This one has one disadvantage. If I am using the Truck class in 100 places, then I need to use the namespace name every time. So always use the alias directive in this scenario.
 
2. Using Statement

This is another way to use the using keyword in C#. It plays a vital role in improving performance in Garbage Collection.
 
What it does actually

The using statement ensures that Dispose() is called even if an exception occurs when you are creating objects and 
calling methods, properties and so on. Dispose() is a method that is present in the IDisposable interface that helps to implement custom Garbage Collection. In other words if I am doing some database operation (Insert, Update, Delete) but somehow an exception occurs then here the using statement closes the connection automatically. No need to call the connection Close() method explicitly.
 
Another important factor is that it helps in Connection Pooling. Connection Pooling in .NET helps to eliminate the closing of a database connection multiple times. It sends the connection object to a pool for future use (next database call). The next time a database connection is called from your application the connection pool fetches the objects available in the pool. So it helps to improve the performance of the application. So when we use the using statement the controller sends the object to the connection pool automatically, there is no need to call the Close() and Dispose() methods explicitly. For more on Connection Pooling, visit the link here.
 
You can do the same as what the using statement is doing by using try-catch block and call the Dispose() inside the finally block explicitly. But the using statement does the calls automatically to make the code cleaner and more elegant. Within the using block, the object is read-only and cannot be modified or reassigned.
 
Let's explain how to implement the using statement in ADO.NET, calling WebService, IO operations, EntityFramework and so on.
 
ADO.NET
  1. string connString = "Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;";  
  2.    
  3. using (SqlConnection conn = new SqlConnection(connString))  
  4. {  
  5.       SqlCommand cmd = conn.CreateCommand();  
  6.       cmd.CommandText = "SELECT CustomerId, CompanyName FROM Customers";  
  7.       conn.Open();  
  8.    
  9.       using (SqlDataReader dr = cmd.ExecuteReader())  
  10.       {  
  11.          while (dr.Read())  
  12.          Console.WriteLine("{0}\t{1}", dr.GetString(0), dr.GetString(1));  
  13.       }  
  14. }  
In the preceding code I am not closing any connection, it will close automatically. The using statement will call conn.Close() automatically due to the using statement (using (SqlConnection conn = new SqlConnection(connString)) and the same for a SqlDataReader object.

And also if any exception occurs it will close the connection automatically.

Entity Framework

The using statement can also be used in EntityFramework and Transcation.
 
Code
  1. public string GetDriver()  
  2. {  
  3.       try  
  4.       {  
  5.             // Creating Transaction object through using statemnt  
  6.             using (TransactionScope trans = new TransactionScope())  
  7.             {  
  8.                   // Creating entity framework connection object through Using statement  
  9.                   using (TruckingDBEntities cc = new TruckingDBEntities ())  
  10.                   {  
  11.                         // Getting employee list  
  12.                         List<emp> empList = (from temp in cc.Employees  
  13.                                                         Where temp.name = “manas”  
  14.                                                         Select temp).ToList();  
  15.                   }  
  16.                // Means all operations are successful and needs to commit.  
  17.                 trans.Complete();  
  18.          }  
  19.    }  
  20.    catch (Exception ex)  
  21.    {  
  22.          // Log error for future reference  
  23.    }  
  24. }   
Web Service

These days a webservice call is often used in our applications. We can also use the using statement when calling a webservice. 
Once we call the webservice if we forgot to dispose of the object then the using statement helps in closing and disposing of the object because webservice objects are heavy.
 
Code
  1. // Calling Webserice with username and password  
  2. using (TruckServiceClient sc = new TruckServiceClient())  
  3. {  
  4.       // Appending username and password to request  
  5.       sc.ClientCredentials.UserName.UserName = "uid";  
  6.       sc.ClientCredentials.UserName.Password = "pwd";  
  7.    
  8.       // Calling webs service method  
  9.       string returndata = sc.GetData(100);  
  10. }  
IO operations

The using statement can also be used when we do any kind of IO operations. It also helps to dispose of IO objects.
 
Code
  1. try  
  2. {  
  3.       using (StreamWriter sw = File.AppendText(filePath))  
  4.       {  
  5.             sw.WriteLine(message);  
  6.       }  
  7. }  
  8. catch(Exception ex)  
  9. {  
  10.    // Handle exception  
  11. }   
  12.    
Lastly we can implement the using statement in custom classes like: 
  1. Class Emloyee  
  2. {  
  3.    Public void getEmp()  
  4.    {  
  5.       // Do some operations  
  6.    }  
  7. }  
Call the Employee class method using the using statement as in the following:
  1. Using(Employee emp = new Employee())  
  2. {  
  3.    emp.getEmp();  
  4. }  
From the preceding discussion you can understand that the using keyword plays a vital role.
 
First, to add a namespace as a type ora  namespace as an alias.

Secondly, to dispose of and close the objects wisely. It enhances the performance of an application.
 
Please extensively use the using statement in projects.
 
I hope it helps you to understand the usage and importance of the using keyword in C#.
 
Happy coding!

Up Next
    Ebook Download
    View all
    Learn
    View all