5

Do I need to use SqlConnection.Open() inside:

using (SqlConnection var = new SqlConnection()) 
{
   //my operations
}

?

What happens if I don't dispose this connection by SqlConnection.Close() function?

1
  • If you don't close or dispose the connection, either by explicitly invoking close/dispose methods or implicitly with a using block, the connection won't get returned to the pool until garbage collection kicks in. Commented Nov 15, 2014 at 13:13

3 Answers 3

15

Yes, you need to Open your connection inside the using block.

If you don't explicitly Close() the connection, the end of the using block will do it for you as the using disposes of the connection. When a connection is disposed it is automatically closed.

Sign up to request clarification or add additional context in comments.

Comments

5

The using statement is just syntactic sugar which ensures that Dispose gets called on the IDisposable instance no matter what, so in your case using (SqlConnection connection = new SqlConnection()) is roughly equivalent to (as per MSDN):

SqlConnection connection = new SqlConnection();

try
{
    // Operations.
}
finally
{
    if (connection != null)
    {
        connection.Dispose();
    }
}

In the case of SqlConnection Dispose and Close calls are actually equivalent, so a call to Close would be redundant within a using (SqlConnection) block.

Calling Open, on the other hand, will still be necessary in many scenarios (before a call to ExecuteReader, ExecuteScalar, ExecuteNonQuery, for example). The using statement has no effect on whether or not you need to explicitly open the connection - only on whether or not you need to explicitly close it.

Comments

0

Provides a convenient syntax that ensures the correct use of IDisposable objects

using Implements IDisposable Internally

using(SqlConnection con=new SqlConnection("myCOnstr")) 
{
con.open();
using(SqlCommand con=new SqlCommand("myCmd",con)) 
{
//......Insert/Update /Delete

}


}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.