1

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"]);
        }
    }
}
7
  • 3
    Possible duplicate of SqlConnection SqlCommand SqlDataReader IDisposable Commented Oct 20, 2016 at 10:09
  • 4
    That for loop is an abomination in the face of man and God. Stick with the first one. Commented Oct 20, 2016 at 10:10
  • @JeroenMostert because? Commented Oct 20, 2016 at 10:12
  • well the for loop should work anyway. But 2nd version doesn't close the reader which is required afaik Commented Oct 20, 2016 at 10:13
  • 2
    @GodofSource: most prominently because it does not explicitly dispose, which things like Code Analysis will warn on (relying on Connection to 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); degenerate for loops are just ugly. But that's a strictly personal preference. Commented Oct 20, 2016 at 10:17

2 Answers 2

2

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 so explicitly in the code.

Sign up to request clarification or add additional context in comments.

Comments

0

The first one will be good.The unwanted resources will be automatically disposed just by calling explicitly

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.