Basic on the "use" of the design

If I use the using construct, I know that the object is automatically deleted. What happens if the expression inside "use" throws an exception. Is the use object still installed? If so, when?

+6
source share
3 answers
Block

A using converted - by the compiler - to this:

 DisposableType yourObj = new DisposableType(); try { //contents of using block } finally { ((IDisposable)yourObj).Dispose(); } 

By placing the Dispose() call in the finally block, it ensures that the Dispose call is always there - unless, of course, an exception is thrown at the instance site, as it happens outside of try .

It is important to remember that using not a special type of statement or construct - it is just that the compiler replaces with something else, which is a little more dumb.

+11
source share

This article explains it well.

Inside, this bad boy generates a try / finally around the selected object and calls Dispose () for you. This eliminates the need to manually create a try / finally block and call Dispose ().

+2
source share

In fact, using a block is equivalent to trying - the final block, which ensures that, finally, it will always be executed, for example.

 using (SqlConnection con = new SqlConnection(ConnectionString)) { using (SqlCommand cmd = new SqlCommand("Command", con)) { con.Open(); cmd.ExecuteNonQuery(); } } 

Equality

 SqlConnection con = null; SqlCommand cmd = null; try { con = new SqlConnection(ConnectionString); cmd = new SqlCommand("Command", con); con.Open(); cmd.ExecuteNonQuery(); } finally { if (null != cmd); cmd.Dispose(); if (null != con) con.Dispose(); } 
+2
source share

All Articles