This may be answered elsewhere, but after doing a bit of searching I didn't find much on the subject outside of the normal using
context.
I am curious if all objects created in a using
block will be disposed of as well as the original object.
Here is the context:
Normally I would do something like this:
using (var conn = new SqlConnection(connectionString))
using (var cmd = new SqlCommand(commandText, conn))
{
//Do everything I need to here
}
I know that both conn
and cmd
go out of scope at this point and are disposed of because of the lovely using
keyword.
I am curious if the same disposal rules would apply to the following statement:
using (var cmd = new (SqlCommand(commandText, new SqlConnection(ConnectionString)))
{
//Do everything I need here
}
Would the SqlConnection
object that was created inline in the using
statment be disposed of when cmd
goes out of scope and is disposed of because it's associated with the object?
Also which would be syntactically preferred? I personally think the 2nd is cleaner, but I understand readability may come to play here as well.
For your second code, Dispose
won't be called on SqlConnection
instance when flow leaves using
block unless SqlCommand.Dispose()
do that internally (and no, it doesn't).
According to specification (8.13), using (ResourceType resource = expression) statement
is transformed into:
{
ResourceType resource = expression;
try {
statement;
}
finally {
if(resource != null)
((IDisposable)resource).Dispose();
}
}
In your code, resource
is SqlCommand
, and that's the one Dispose
is called on.