4

What does

using (SqlConnection cn = new SqlConnection(connectionString))

do?

5 Answers 5

13
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(); }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

2

Makes sure the SqlConnection is destroyed at the end of the "using" scope

Comments

1

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

Comments

0

This ensures releasing connection when control leaves using() {..} clause.

Leaving may occur as a result of exception, function return, break from loop, goto or normal leaving of scope. Very convenient.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.