Wednesday, March 25, 2009

Advantage of "using" keyword C#

if u declare any managed/un-managed object in using block,
u don't need to explicitely dispose those object.. once the block execution is over, the Dispose will be called automatically.

using (SqlConnection cn = new SqlConnection(connectionString))
{// do something}

is the same as:

SqlConnection cn = new SqlConnection(connectionString)
try
{// do something...}
finally
{cn.Dispose();}
The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. 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. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block;

No comments: