vendredi 14 août 2015

use using to dispose or resources

I am just starting to use "using" to make sure resources are disposed regardless of what happens.

Below is an example of some code that I have written to retrieve some data. My question is are all the "using" required or would it be enough to just have the first one?

        SomeMethod()
        {
            using (SqlConnection cn = new SqlConnection("myConnection"))
            {
                cn.Open();

                using (SqlCommand cmd = cn.CreateCommand())
                {
                    cmd.CommandText = "myQuery";
                    using (SqlDataReader rdr = cmd.ExecuteReader())
                    {
                        if(rdr.HasRows)
                        {
                            while (rdr.Read())
                                // do something
                        }
                    }
                }
            }
        }



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire