I use the using statement for SqlConnection. It’s is good for performance because forces calling Dispose() that simply releases the connection to the pool sooner.
However, I realized that object created in using cannot be redefined. I cannot do like this:
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
//...
connection = new SqlConnection(connectionString2);
//...
connection = new SqlConnection(connectionString3);
}
I was wondering if I can replace using, and do something like this:
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
//...
connection = new SqlConnection(connectionString2);
//...
connection = new SqlConnection(connectionString3);
}
The SqlConnection will not be accesible after last } brace. Will be the Dispose() called immediatly when object goes out of scope?
No, things won’t get automatically cleaned up in your second example (in fact, with the code you have, you’ll leave several connections hanging open).
Not only that, but you lose the automatic cleanup in case of Exceptions being thrown inside the
usingblock. Remember that ausingblock decomposes into:If you’re really using different connections and each connection is Disposed of at the end of the block, I would use several using blocks: