Is it correct to use a using block inside another using block?

15

Is it correct to use a block using within another block using as in the example below? or is it enough to just put the first using ?

    public DataTable Listar(string stringMySql, CommandType commandType, List<MySqlParameter> lstParametros)
    {
        using (MySqlConnection mySqlConnection = new MySqlConnection())
        {
            mySqlConnection.ConnectionString = StaticKey.RetornaStringConexao();
            mySqlConnection.Open();

            using (MySqlCommand mySqlCommand = new MySqlCommand())
            {
                mySqlCommand.Connection = mySqlConnection;
                mySqlCommand.CommandType = commandType;
                mySqlCommand.CommandText = stringMySql.Trim();

                if (lstParametros != null)
                {
                    mySqlCommand.Parameters.AddRange(lstParametros.ToArray());
                }

                using (DataTable dataTable = new DataTable())
                {
                    using (MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter(mySqlCommand))
                    {
                        mySqlDataAdapter.Fill(dataTable);

                        return dataTable;
                    }
                }
            }
        }
    }
    
asked by anonymous 02.12.2015 / 15:07

1 answer

12

It is absolutely correct. Each resource needs its own using to ensure it is closed when it is no longer needed. You can improve here a bit:

using (DataTable dataTable = new DataTable())
using (MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter(mySqlCommand)) {
    mySqlDataAdapter.Fill(dataTable);
    return dataTable;
}

You can only use one block with more than one open resource. At the end of the block, both will be shut down.

Actually there is a problem there. The code is returning something being laid out. This will not work. If you are going to return the resource out of the method, you can not dispose of it. In this case, the using should not be used for the feature to remain alive. So:

DataTable dataTable = new DataTable();
using (MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter(mySqlCommand)) {
    mySqlDataAdapter.Fill(dataTable);
    return dataTable;
}

Or in some cases (not in this):

DataTable dataTable = new DataTable();
try {
    using (MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter(mySqlCommand)) {
        mySqlDataAdapter.Fill(dataTable);
        return dataTable;
    }
} finally {
    if (dataTable != null) {
        dataTable.Dispose();
    }
}
    
02.12.2015 / 15:10