close or dispose (using statement) ADO.NET connection

During the code-review, a question arose if we need to call close() within the using statement of ado.net connection. The answer is no. using statement calls dispose() at the end and dispose() calls close() inside. You can check it in reflector.

protected override void Dispose(bool disposing)
{
    if (disposing)
    {
        this._userConnectionOptions = null;
        this._poolGroup = null;
        this.Close();
    }
    this.DisposeMe(disposing);
    base.Dispose(disposing);
}

C# compiler converts “using” statement into try and catch block and simplifies your code (http://msdn2.microsoft.com/en-us/library/ms998569.aspx)

using (SqlConnection conn = new SqlConnection(connString))
{
  conn.Open();
  . . .
} // Dispose is automatically called on the conn variable here
SqlConnection conn = new SqlConnection(connString);
try
{
  conn.Open();
}

finally
{
  conn.Dispose();
}
close or dispose (using statement) ADO.NET connection

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 )

Google+ photo

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

Connecting to %s