forum

Home / DeveloperSection / Forums / SqlConnection SqlCommand SqlDataReader IDisposable

SqlConnection SqlCommand SqlDataReader IDisposable

Anonymous User287119-Jun-2013
Hi,

SqlConnection, SqlCommand and SqlDataReader all implement the IDisposable interface. I read about a best practice to always wrap IDisposables into a using block.

So, my common scenario for querying data would look something like this (in greater context of course a mapping tool like linq2sql would be suitable, but lets just assume we want to use this approach here):

using (SqlConnection cn = new SqlConnection("myConnectionstring"))
{
    using (SqlCommand cm = new SqlCommand("myQuery", cn))
    {
        // maybe add sql parameters
        using (SqlDataReader reader = cm.ExecuteReader())
        {
             // read values from reader object
             return myReadValues;
        }
    }
}


Is this the correct way or could that be considered overkill? I am a little unsure about this level of nesting using blocks, but of course i want to do it the correct way. Thanks!

Updated on 19-Jun-2013
I am a content writter !

Can you answer this question?


Answer

1 Answers

Liked By