mHelpMe
mHelpMe

Reputation: 6668

Use using to dispose resources

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
                        }
                    }
                }
            }
        }

Upvotes: 4

Views: 134

Answers (3)

Fabjan
Fabjan

Reputation: 13676

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 :)

Upvotes: 4

f14shm4n
f14shm4n

Reputation: 461

Are all the "using" required or would it be enough to just have the first one?

If any object which you use is implementing IDisposable, you can use using statement, which will auto-disposing your object, or you can disposing (closing for any streams and etc) your object manually without using, just calling Dispose().

So, for all objects which can be disposed better use using statement.

Upvotes: 1

Felix K.
Felix K.

Reputation: 6281

Using is a shortcut for the following pattern:

IDisposable resource = .....;
try
{
}
finally
{
    if (resource != null)
        resource.Dispose();
}

I would strongly suggest to use using always when using resources which need to be disposed or have the IDisposable interface implemented. Reason is that you don't know the implementation behind and it's much safer this way to prevent memory leaks or other code issues.

Upvotes: 2

Related Questions