Guidelines for "using" with ADO.NET components

Hi everyone,

I know how to use the "using" statement but I'm a little confused about exactly when to use it with the ADO.NET components. Let's say I have a SqlConnection, SqlCommand, SqlDataReader. Should I use using with all of them, like this?

using (SqlConnection conn = new SqlConnection(...))

{

using (SqlCommand cmd = new SqlCommand(...))

{

using (SqlDataReader rdr = cmd.ExecuteDataReader())

{

}

}

}

Or do I only need to use "using" on the outermost construct (in this case, the connection), or what are the best practices for this?

-Eric Harmon

[659 byte] By [EricHarmon] at [2007-12-28]
# 1

a using block suppose to call the Dispose method of the Object used in using block. I mean using (SqlCommand cmd = new SqlCommand). It will call dispose method of SqlCommand after completing the using block.

If you are using in SqlDataReader, SqlCommand and SqlConnection object I would recommend that u also call Close() method of each of this object.

Bappi at 2007-9-4 > top of Msdn Tech,.NET Development,.NET Framework Data Access and Storage...
# 2

Yes, I know what the using block does. I'm wondering if I should really be calling it for all three objects (SqlConnection, SqlCommand, SqlDataReader) or maybe only for the connection - most samples I've seen only appear to use it for the connection.

I don't think I need to call Close(), because the using block guarantees that the connection will be closed.

I'm wondering if when the connection is closed it also forces the data reader and command to be disposed as well. It feels safer to me to put the using block around all three of them, but I've seen what I believe are complete examples (not shortened for readability in other words) that only put the using block around the connection.

EricHarmon at 2007-9-4 > top of Msdn Tech,.NET Development,.NET Framework Data Access and Storage...
# 3

It is preferable to use "using" because:

1) It is easier to read and understand the code. At the same time it is easier to support (let's say "modify") the code.
2) Reader does not closes the connection itself (of course, you can set behaviors to the reader, but iI mean generally)

BTW you can use your SqlCommand object without "using" because its Dispose method does not impact the Connection object. But it cleans its internal cache when disposing so I prefere to use "using".

AlexeyRaga at 2007-9-4 > top of Msdn Tech,.NET Development,.NET Framework Data Access and Storage...

.NET Development

Site Classified