2

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
KWallace
  • 1,570
  • 1
  • 15
  • 25
  • 2
    Yes, it will, because it calls `Dispose` at the end in a `finally`, which calls `Close`. Do take note that if `.Open()` is called before the `using`, there is a risk of leaking resources, since an exception could occur that prevents the `using` from ever being entered. – Jeroen Mostert Dec 04 '22 at 19:36
  • What do you mean by "Except I am wondering about using the actual connection, not a copy of it."? There is nowhere a copy used. – Ralf Dec 04 '22 at 20:33
  • @Ralf Consider it a "reference to it" instead, then. That's probably more accurate. – KWallace Dec 05 '22 at 23:11

1 Answers1

4

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
Moshe Katz
  • 15,992
  • 7
  • 69
  • 116