Using statement in C# (ASP.NET)

When you are dealing with objects in c#, you have to make sure that when you are done with the object, the object's Dispose method is called.

This can be done using try and finally blocks, where you use the object in try Block and destroy the object in finally block. But this can be easily done by "using" statement.

The using statement gets translated into a try and finally block. A using statement is translated into three parts: acquisition, usage, and disposal. The resource is first acquired, then the usage is enclosed in a try statement with a finally clause. The object then gets disposed in the finally clause. For example the following lines of code using the using statement,


Normally in the try catch block we would have written:

SqlConnection con;
try
{
    con=new Sqlconnection(connectionString);
}
catch
{
       //Do Something with the exception..
}
finally
{
    con.close();  //Disposing the object manually.
}

But using block has made this simple(rather to dispose objects manually) :

using(SqlConnection con=new Sqlconnection(connectionString))
{
      con.open();
      //Do Some Operation
}

And now, you dont need to worry about the object's memory release; since using block takes care of it automatically by invoking con.close() and everyother object that is used inside it.. :)

And thus, it helps us in managing the memory in a more efficient way..

Note: One advantage with the using block is that, even in the case if the statements in that block raises an exception, that block disposes the memory.. And thats good of it.. And even we need to look at the cons of it like: what if there is an error while acquiring the source? (like if we use the filestream), in that case we should use using block nested inside the try-catch block... :)


1 comment: