I have a question about C# using
statement. According to the docs, it is a best practice to both declare and initialize the resource (for instance, a SqlConnection
object) inside the using statement. My question is: if I'll only declare the object outside the using scope (and initialize it as part of the using statement), is it completely equal to declaring it as part of the using
statement? My use case is that I need to use an SqlConnection
object outside the using scope. (I would like to call SqlConnection.ClearPool
on it, in case I get some specific exception.
Both scenarios are equivalent. But when you declare a variable outside the scope of the using statement, the variable will get disposed after the completion of the using statement's scope but still remain in scope. Accidental use of the variable after the using statement's scope may lead to exception to be thrown. This is considered to be bad practice and is avoided. I have never had reason to declare the variable before the using statement.