How and why to use Using statement in C#?

 Posted by Raja on 3/3/2009 | Category: C# Interview questions | Views: 32524

Using statement is used to work with an object in C# that inherits IDisposable interface.

IDisposable interface has one public method called Dispose that is used to dispose off the object. When we use Using statement, we don't need to explicitly dispose the object in the code, the using statement takes care of it. For eg.

Using (SqlConnection conn = new SqlConnection())



When we use above block, internally the code is generated like this
SqlConnection conn = new SqlConnection()


// calls the dispose method of the conn object

Using statement make the code more readable and compact.

For more details read

Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Posted by: Akiii on: 10/10/2011 | Points: 10
Simple and nice explanation..

Thanks and Regards
Posted by: Robertgalp on: 6/27/2014 | Points: 10
Placing your code inside a using block ensures that it calls Dispose() method after the using-block is over, even if the code throws an exception.

using (someClass sClass = new someClass())



Login to post response