Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use using to dispose resources

Tags:

c#

.net

I just started 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
                        }
                    }
                }
            }
        }
like image 504
mHelpMe Avatar asked Mar 15 '23 02:03

mHelpMe


1 Answers

Using is nothing else than :

SomeClass o = null;
try 
{ 
   // managed resource that you use
   o = new SomeClass();  
   // ... some other code  here
}
finally 
{
  if(o != null)
    o.Dispose();
}

There is nothing wrong with a fact that you use using statement when it is possible (class implements IDisposable interface). When you want to use some managed resource then use using :)

like image 158
Fabjan Avatar answered Mar 28 '23 07:03

Fabjan