11 July 2012

Use of Using Statement in C#


Use of Using Statement in C#

In C#, using Keyword is used in two different ways and are hence referred to differently.
 As a Directive
In this usage, the "using" keyword can be used to include a namespace in your program. (Mostly used)
As a Statement
Using can also be used in a block of code to dispose an IDisposable objects.

SqlConnection connection = new SqlConnection("connection string");
SqlCommand cmd = new SqlCommand("SELECT * FROM SomeTable", connection);
SqlDataReader reader = cmd.ExecuteReader();
connection.Open();
if (reader != null)
{
      while (reader.Read())
           {
                          //do something
           }
}
reader.Close(); // close the reader
connection.Close(); // close the connection

  
Disadvantages of the above code:

If any exception occurs inside while block it throws exception, the connection.close() process will not executed due to the exception. To avoid this situation, we can take the help of the try....catch... finally block   by closing the connection inside the finally block or inside the catch block.

Advantages of the below code:

"Using" keyword takes the parameter of type IDisposable. Whenever you are using any IDisposable type
object you should use the "using" keyword to handle automatically when it should close or dispose.
Internally using keyword calls the Dispose() method to dispose the IDisposable object.

using (SqlConnection connection = new SqlConnection("connection string"))
{

connection.Open();
using (SqlCommand cmd = new SqlCommand("SELECT * FROM SomeTable", connection))
{

   using (SqlDataReader reader = cmd.ExecuteReader())
   {
         if (reader != null)
        {
             while (reader.Read())
                {
                   //do something
                }
         }
   } // reader closed and disposed up here

// command disposed here
//connection closed and disposed here

No comments:

Post a Comment

Comments Welcome

Consistency level in Azure cosmos db

 Consistency level in Azure cosmos db Azure Cosmos DB offers five well-defined consistency levels to provide developers with the flexibility...