God of Source God of Source - 1 month ago 19
C# Question

Proper use of SqlDataReader

I've seen 2 examples of

SqlDataReader


The first one has a using which manages the disposal of the connection and the used memory, and the second has less code.

Which one is to prefer?

using (SqlConnection myConnection = new SqlConnection(ConnectionString))
{
myConnection.Open();
using (SqlCommand cmd = new SqlCommand("SELECT Name FROM User;", myConnection))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
DoStuff((string)reader["Name"]);
}
}
}
}


second one :

using (SqlConnection mConnection = new SqlConnection(ConnectionString))
{
mConnection.Open();
using (SqlCommand cmd = new SqlCommand("SELECT Name FROM User;", mConnection))
{
for (SqlDataReader reader = cmd.ExecuteReader(); reader.Read(); )
{
DoStuff((string)reader["Name"]);
}
}
}

Answer

the second has less code.

Not really.

Which one is to prefer?

The first one, by far. But just for esthetic reasons.

In the second sample, the Reader will be closed when it's (owning) connection is Disposed but it is far better to do this explicitly in the code.

Comments