Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

What does

using (SqlConnection cn = new SqlConnection(connectionString))

do?

like image 282
Ramesh Avatar asked Nov 30 '22 18:11

Ramesh


1 Answers

new SqlConnection(connectionString)

creates a new SqlConnection instance against the supplied connection string.

SqlConnection cn = ...

assigns it to the new local variable cn (scoped to the using statement) that holds the constructed connection object.

using(...)

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

The whole 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(); }
    }
}
like image 97
Marc Gravell Avatar answered Dec 16 '22 23:12

Marc Gravell