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"]);
}
}
}