What does
using (SqlConnection cn = new SqlConnection(connectionString))
do?
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(); }
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With