views:

62

answers:

3

Can you use 2 'using' statements like:

using (SqlConnection ..)
{
    using(SqlDataReader reader = new SqlDataReader())
    {

     }

}

I'm trying to do this put getting an error on the constructor of the SqlDataReader

+1  A: 

You can and you can also format them without the extra brackets like so:

using (SqlConnection ..)
using(SqlDataReader reader = new SqlDataReader())
{

}

Which I do all the time to limit the amount of scope nesting.

dkackman
wow, I didn't know about the avoidable {}. handy . . .
Patrick Karcher
This is still wrong, and will still throw the same error.
ck
Whatever your error is, it is unrealted to using two using statements.
dkackman
+6  A: 

SqlDataReader has no constructor. You are returned a datareader by calling the ExecuteReader method of a SqlCommand object.

e.g.

using (SqlConnection ..) 
{ 
    SqlCommand cmd = new SqlCommand(...);
    using(SqlDataReader reader = cmd.ExecuteReader())) 
    { 

    } 

}
ck
FYI: SqlCommand is IDisposable and should be in a using statement as well.
dkackman
A: 

You can't instantiate a SqlDataReader like that as mentioned above. Generally I see 2 levels of using blocks, but the inner one would be the command object, something like this:

 using (var conn = new SqlConnection(...))
 {
    conn.Open();
    using (var cmd = new SqlCommand(...))
    {
       var rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
    }
 }
jaltiere