1.

What is the use of using keyword?

Answer»

There are two ways to USE the using keyword in C#. One is as a directive and the other is as a statement.

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:

  • To allow the NORMAL use of types in a namespace:
    • using System.IO;  
    • using System.Text;  
  • To create an alias for a namespace or a type. This is called a using alias directive. 
    • using MyProject = TruckingApp.Services; 

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.

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 Example:

   string connString = "Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;";      using (SqlConnection conn = new SqlConnection(connString))      {          SqlCommand cmd = conn.CreateCommand();            cmd.CommandText = "SELECT CustomerId, CompanyName FROM Customers";            conn.Open();            using (SqlDataReader dr = cmd.ExecuteReader())            {             while (dr.Read())               Console.WriteLine("{0}\t{1}", dr.GetString(0), dr.GetString(1));            }    }


Discussion

No Comment Found