Friday, 4 October 2013

Use of using statement in c#

  • using is used when you have a resource that you want disposed after it's been used.
  • The using statement obtains the resource specified, executes the statements and
    finally calls the Dispose method of the object to clean up the object.
  • This is basically used to release the  Resources that are no longer in use.
  • When the code block exits the scope of the using statement, Dispose() is called implicitly.
using (SqlConnection con = new SqlConnection(AppConfiguration.ConnectionString))
            {

            }

The above block implicitily convert as follwoing

try
{
SqlConnection con = new SqlConnection(AppConfiguration.ConnectionString)
}
finally
{
if(con!=null)
{
 ((IDisposable)con).Dispose();
}
}

No comments:

Post a Comment