Saturday, January 17, 2009

using Statement in C#

using statement is a very important feature supported by C#. It ensures no Memory Leak and no Exceptions due to unmanaged resources. It is very important to free the memory once object is used and is not needed anymore, or to Dispose the resource. using statement does the same thing for you allowing coder to concentrate on other aspects of the project taking responsibility to free the resources occupied.

generally this is used for all places where we are using a connection to the underlaying datasource.


using ( SqlConnection connection = new SqlConnection(connectionString) )
SqlCommand cmd = new SqlCommand(commandString, connection);
using (SqlDataReader reader = cmd.ExecuteReader())
while (reader.Read())
// TODO : Do some work with each record.

Here, the SqlDataReader object is created with "using" statement, and hence there's no need to close the reader and underlaying connection explicitly. If we use the ILDASM to see the generated IL Code, we can see the using statement calling the Dispose method. If we don't use the "using" statement, then the alternative way is to use try-catch-finally block to ensure no exception thrown and resources are freed, that contains more code than the code block above. compare the code block below.

It's a always a good practice to use using statement, when using an IDisposable object. The using statement calls the Dispose method on the object in the correct way, and it also causes the object itself to go out of scope as soon as Dispose is called and allow GC to do his job. Within the using block, the object is read-only and cannot be modified or reassigned.

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object.

* using Directive is used differently than using Statement
* Other Usage of using Statement

No comments:

Post a Comment