Subhash Sharma

Subhash Sharma
Subhash Sharma

This is Subhash Sharma(Software Engineer) Blog

Welcome to this blog and find every solution.............

Search This Blog

Software Engineer(Subhash Sharma)

Software Engineer(Subhash Sharma)
Software Engineer

Tuesday, March 15, 2011

Using Statement in C#

Using block defines a scope, outside of which an object or objects will be disposed.
The using statement takes an object parameter, this object is destroyed when the statement finish's, or rather disposed of (IDisposable). The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources.
A "using" statement can be exited either when the end of the "using" statement is reached or if an exception is thrown and control leaves the statement block before the end of the statement.
In the below example font1 object is disposed of after the using statement has been executed.
using (Font font1 = new Font("Arial", 10.0f)){}
Multiple objects can be used in with a "using" statement, but they must be declared inside the "using" statement, like this:
using (Font font3 = new Font("Arial", 10.0f),
font4 = new Font("Arial", 10.0f)){
// Use font3 and font4.
}



The problem is that SqlConnection and SqlCommand implement IDisposable, which means they could have unmanaged resources to cleanup and it is our job, the developers, to make sure Dispose() gets called on these classes after we are finished with them. And, because an exception could be raised if the database is unavailable ( a very real possibility on WebHost4Life :) ), we need to make sure Dispose() gets called even in the case of an exception.

Personally, I like the “using” keyword in C#. Internally, this bad boy generates a try / finally around the object being allocated and calls Dispose() for you. It saves you the hassle of manually creating the try / finally block and calling Dispose().

The new code would looking something like this:

using (SqlConnection cn = new SqlConnection(connectionString))
{
using (SqlCommand cm = new SqlCommand(commandString, cn))
{
cn.Open();
cm.ExecuteNonQuery();
}
}

This is essentially equivalent to the following, although my guess is that C# will internally generate two try / finally blocks (one for the SqlConnection and one for the SqlCommand), but you get the idea:

SqlConnection cn = null;
SqlCommand cm = null;

try
{
cn = new SqlConnection(connectionString);
cm = new SqlCommand(commandString, cn);
cn.Open();
cm.ExecuteNonQuery();
}
finally
{
if (null != cm);
cm.Dispose();
if (null != cn)
cn.Dispose();
}

No comments:

Post a Comment