I have the following code:
SqlConnection Connect = new SqlConnection(IST_DBConnect.SQLConnectionString);
SqlCommand command = new SqlCommand(sqlCommandString, Connect);
RequestRow Result = new RequestRow();
Connect.Open();
using (Connect)
...
This is not my code, I would write the creation of the SQL Connection in a using statement, this is a code of my friend, I am no exactly sure if this is going to dispose properly the SQL connection object if something goes wrong in the constructor or in the Open method. So my question is if the connection object is created and the open method throws an exception => the connection is never opened, will this be disposed properly?
Thanks.
From documentation;
As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement.
and
You can instantiate the resource object and then pass the variable to the using statement, but this is not a best practice. In this case, the object remains in scope after control leaves the using block even though it will probably no longer have access to its unmanaged resources. In other words, it will no longer be fully initialized. If you try to use the object outside the using block, you risk causing an exception to be thrown. For this reason, it is generally better to instantiate the object in the using statement and limit its scope to the using block.
Based on your example, if somethings goes wrong in constructor, of Open
method, there is nothing using
can do since you use it as a resource after you initialize it.
Sure this is the best way;
using(var Connect = new SqlConnection(IST_DBConnect.SQLConnectionString))
using(var command = Connect.CreateCommand())
{
//
} // <-- Both Connect and command will disposed here no matter exception is thrown or not