3

I want to use the "using" block in my DAL layer. Like

using (SqlConnection con = new SqlConnection("connection string"))
{
     Command object
     Reader object
}

Since the SqlConnection object in initialised in the using block i know that this connection object will be automatically disposed when the control exits the using block scope.

But i am creating Command and Reader objects inside the using block. Do i have to explicitly close them or do i have to write another "using" block for them.

2
  • Not sure.But need not write another "using" block.After block scope is over objects:Command & Reader will be disposed. Commented Dec 20, 2010 at 7:50
  • @Pratik, only object explicitly put in the using (...) parentheses are actually disposed. Here, the Command and Reader will not be disposed. Commented Dec 20, 2010 at 9:36

5 Answers 5

4

You should use using for the Command and Reader as well, or explicitly close them.

I normally code it like this:

var sql = "SELECT * FROM table";
using (var cn = new SqlConnection(connectionString))
using (var cmd = new SqlCommand(sql, cn)) {
}

This limits the number of identations.

Sign up to request clarification or add additional context in comments.

Comments

3

You typically write using-blocks for those as well, ie.

using (SqlConnection con = new SqlConnection("connection string"))
{
    con.Open();
    using (SqlCommand cmd = con.CreateCommand())
    {
        cmd.CommandText = "select * from table";
        using (SqlDataReader reader = cmd.ExecuteReader())
        {
            ...
        }
    }
}

Comments

2

It's worth writing a using block for any code that supports IDisposable interface. This way you ensure that you have done what you can to release any scarce resources.

Comments

1

You can make using blocks for any item that implements IDispose. So you can make nested using blocks for each of these, within the block for the connection, to ensure that they are properly disposed of after use.

Comments

0

You should use using() or finally blocks if you don't like using for your connections and readers. For readers, connection isn't closed until the reader is closed. Also I've read that using() doesn't 100% guarantee you that the connection will be closed but I don't know the reason behind that since it is converted to try - finally blocks and will be executed in any condition.

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.