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"]);
}
}
}
forloop is an abomination in the face of man and God. Stick with the first one.Connectionto do it is anything but obvious). Less prominently because it has no third statement (as advancing the reader and checking for termination are the same thing); degenerateforloops are just ugly. But that's a strictly personal preference.