5

If you employ a using clause to dispose of a connection, are other items within the clause that implement IDisposable also automatically disposed? If not, how do you handle making sure all IDisposable items are automatically disposed?

public static DataTable ReturnDataTable(
    string ConnectionString, string CommandTextString, CommandType CommandType, 
    int CommandTimeout, List<System.Data.SqlClient.SqlParameter> ParameterList = null)
{
    using (System.Data.SqlClient.SqlConnection Connection =
        new System.Data.SqlClient.SqlConnection())
    {
        Connection.ConnectionString = ConnectionString;

        System.Data.SqlClient.SqlCommand Command =
            new System.Data.SqlClient.SqlCommand();
        Command.Connection = Connection;
        Command.CommandText = CommandTextString;
        Command.CommandType = CommandType;
        Command.CommandTimeout = CommandTimeout;

        if (ParameterList != null)
        {
            if (ParameterList.Count > 0)
            {
                foreach (SqlParameter parameter in ParameterList)
                {
                    Command.Parameters.AddWithValue(
                        parameter.ParameterName, parameter.Value);
                }
            }
        }

        System.Data.DataTable DataTable = new System.Data.DataTable();

        System.Data.SqlClient.SqlDataAdapter DataAdapter =
            new System.Data.SqlClient.SqlDataAdapter();
        DataAdapter.SelectCommand = Command;
        DataAdapter.Fill(DataTable);

        return DataTable;
    }
}
1
  • Why don't you use another form of using: using System.Data.SqlClient;? Commented Apr 25, 2011 at 2:02

3 Answers 3

7

You can stack the statements like this (to initialize all disposable objects early on)

using (...)
using (...)
{
  ...
}

or you can use nested using statements for each disposable object you need

using (...)
{
   using (...) { ... }
   using (...) { ... }
}
Sign up to request clarification or add additional context in comments.

Comments

3

Only an object created in the using clause will be disposed. If you want to make sure that call to dispose is automatically generated for every disposable object created inside of the using block you will need to wrap each of them in a using clause (or you can just call dispose or close, whichever they support, of course). So, the answer is not.

Comments

2

No. You will have to explicitly call Dispose on the ones that are not inside the parameters of the using statement.

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.