Search code examples
c#using-statement

What is the use of the using block?


In which situation can a using block be used and what are the benefits?

using (some code statement here) 
{
    //code here
}

Solution

  • Using blocks are only useful when utilizing objects that implement IDisposable. (Try saying that 5 times fast). It ensures that the dispose methods of those objects are called after they fall out of scope.

    using(SqlConnection con = new SqlConnection(this.connString))
    {
        //do stuff here
    } //con.Dispose() will be called for you automatically.