Are ALL the sqlCommand, sqlTransaction and sqlDataAdapter objects automatically disposed on exit from the "using" block (in which sqlConnection disposed) or all these objects to be disposed should be in separated nested "using" blocks, otherwise these objects will not be disposed when sqlConnection object disposed? What are the best practices?
public static void ExecuteDataset(string connectionString, string storedProcedure, SqlParameter[] sqlParameters = null)
{
SqlTransaction sqlTransaction = null;
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
try
{
sqlConnection.Open();
SqlCommand sqlCommand = new SqlCommand(commandText, connection);
command.Parameters.Add("@ID", SqlDbType.Int);
sqlCommand.Connection = sqlConnection;
SqlTransaction = sqlConnection.BeginTransaction();
sqlCommand.Transaction = sqlTransaction;
.....................................................
.....................................................
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
................................
................................
sqlTransaction.Commit();
}
catch (Exception)
{
sqlTransaction.Rollback();
}
}
}
usingblock. Anything else is a shortcut that you can do... but it's simply sloppy programming and will fall apart if you change something (like for example your database provider).IDisposableso you should put them in a using block. That way, they will be handled properly, whatever the database vendor considers "properly".