What this code does: using (SqlConnection cn = new SqlConnection (connectionString))

What is he doing

using (SqlConnection cn = new SqlConnection(connectionString)) 

do?

+4
source share
6 answers
 new SqlConnection(connectionString) 

creates a new SqlConnection instance against the attached connection string.

 SqlConnection cn = ... 

assigns it a new local variable cn (attached to the using statement), which contains the constructed connection object.

 using(...) 

It is a using statement - it ensures that the Dispose() -d connection is at the end, even if an exception is thrown (in this case, Dispose() means closing / releasing it to the pool, etc.)

All code is essentially:

 { // this { } scope is to limit the "cn" SqlConnection cn = new SqlConnection(connectionString); try { // the body of the using block ... } finally { // dispose if not null if(cn != null) { cn.Dispose(); } } } 
+13
source

Installs SqlConnection after it is no longer needed. In this case, SqlConnection may leave some unmanaged resources behind, and you must clear them. SqlConnection implements IDisposable , which means that you can (should) call Dispose after you finish working with it.

This is mainly a reduction for:

 try { SqlConnection cn = new SqlConnection(connectionString); // whatever other code } finally { if (cn != null) { cn.Dispose(); } } 

When you use using , the scope of cn expands beyond try (to finally ).

If you want to know more, check the MSDN article for this topic.

+4
source

Assures that SqlConnection will be destroyed at the end of the scope

+2
source

The using statement can be applied to objects that implement the IDisposable interface. At the end of the scope, Dispose is invoked on the object.

+1
source

Here are some links to doco MSDN:

Using an operator .

class SqlConnection .

+1
source

This ensures that the connection is released when the control goes out of use () {..}.

Exit can occur as a result of an exception, function return, exit from the loop, goto, or the usual exit from the scope. Very comfortably.

0
source

Source: https://habr.com/ru/post/1311384/


All Articles