Use to recycle resources

I just started using “use” to make sure that resources are located no matter what happens.

Below is an example of the code I wrote to get some data. My question is:

Is all "use" required or would it be enough to have only the first?

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 } } } } } 
+4
source share
3 answers

Use is nothing more 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 using when statement when possible (the class implements the IDisposable interface). If you want to use some managed resource, use with :)

+4
source

Usage is a shortcut for the following template:

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

I would highly recommend using using always when using resources that need to be removed or implement the IDisposable interface. The reason is because you do not know the implementation, and it is much safer to prevent memory leak or other code problems.

+2
source

Is all "use" required or would it be enough to have only the first?

If any object that you use implements IDisposable , you can use the using statement, which will automatically delete your object, or you can manually delete (close for any threads, etc.) your object without using , just calling Dispose() .

So, for all objects that might be located better, use the using statement.

+1
source

All Articles