Search code examples
c#sql-serversqlconnectionsqlcommand

Will a SqlConnection() declared before using it in a using() statement still close the connection when done? (C#/SQL Server)


In a situation like this:

SqlConnection cn = new SqlConnection(
    ConfigurationManager
    .ConnectionStrings["AppConnection"]
    .ConnectionString
);


using (cn) {...}

Will the using() statement still close the connection even though it wasn't declared in the using() statement?

Similar to this question: SqlConnection with a using clause - calling close on the connection

Except I am wondering about using the actual connection, not a copy of it.


Solution

  • Yes, but you shouldn't do it.

    The documentation for using says (all the way at the bottom):

    You can instantiate the resource object and then pass the variable to the using statement, but this isn't a best practice. In this case, after control leaves the using block, the object remains in scope but probably has no access to its unmanaged resources. In other words, it's not fully initialized anymore. If you try to use the object outside the using block, you risk causing an exception to be thrown. For this reason, it's better to instantiate the object in the using statement and limit its scope to the using block.

    var reader = new StringReader(manyLines);
    using (reader)
    {
        ...
    }
    // reader is in scope here, but has been disposed