What is the advantage of “Using” keyword in asp.net?


Maximum new programmer used to write code without calling Dispose() on sqlconnection and sqlcommand  object. Even thought I was also writing code like this.

 

SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(commandString, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();

 

But SqlConnection and SqlCommand implement IDisposable, which means they could have unmanaged resources to cleanup and it is our job, to make sure Dispose() gets called on these classes before finishing the task. Otherwise an exception could be raised if the database is unavailable,we need to make sure Dispose() gets called even in the case of an exception.

There are 2 methods to cleanup the resources

  1. Using C# “Using” Keyword.
  2. Using Try/ Finally

Syntax for “Using” keyword

 

using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(“ SQL Query ”, con))
{
con.Open();
cmd.ExecuteNonQuery();
}
}

 

Syntax  for using  “Try/Finally”

 

SqlConnection con =  null;
SqlCommand cmd = null;

try
{
con = new SqlConnection(connectionString);
cmd = new SqlCommand(“SQL QUERY”, con);
con.Open();
cmd.ExecuteNonQuery();
}
finally
{
if (null != cmd);
cmd.Dispose();
if (null != con)
con.Dispose();
}

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.