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(); }
}
}
It disposes the SqlConnection after it's not needed anymore. In this case SqlConnection can leave some unmanaged resources behind and you should clean them up. SqlConnection implements IDisposable, which means you can (should) call Dispose after you are done working with it.
It's basically a shorthand for:
try {
SqlConnection cn = new SqlConnection(connectionString);
// whatever other code
}
finally {
if (cn != null)
{
cn.Dispose();
}
}
When you use using, scope of cn is extended also outside try (to finally).
If you want to learn more, check MSDN's article regarding this topic.