using keyword

  • Thread starter Thread starter Mike P
  • Start date Start date
M

Mike P

I've recently started using the using keyword for my connections, but I
have just seen some code where you have a using within a using, which is
opening a command :

using (SqlConnection _conn = new
SqlConnection(ConfigurationManager.ConnectionStrings["constreng"].ToStri
ng()))
{
using (SqlCommand _comm = new
SqlCommand("GetRevenueByOwner", _conn))
{

Is it good practice to use something like this?
 
Mike,

Yes, it is, since you are disposing of the command when you are done
with it. There is nothing wrong with nested using statements.

The only thing you have to worry about is if an object in a nested
statement uses an object in the outer statement, and you want to use that
outer object after the inner object is done. It is possible that the inner
object will call dispose in it's implementation of Dispose.

In your example:

using (SqlConnection _conn =
new
SqlConnection(ConfigurationManager.ConnectionStrings["constreng"].ToString()))
{
using (SqlCommand _comm = new SqlCommand("GetRevenueByOwner", _conn))
{

}

// Do something with _conn here
}

You don't have a problem with using _conn, since the command doesn't
dispose of the connection when Dispose is called on it. However, for
something like a TextReader attached to a stream, you might run into this.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top