In regards to the following code:
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
code...
}
Is the SqlConnection initialized with "using" so it is dereferenced/destructed after the brackets?
Please correct my questioning where necessary.
using
is a syntactical shortcut for correctly calling Dispose()
on the object.
After the code in the braces is finished executing, Dipose()
is automatically called on the object(s) wrapped in the using
statement.
At compile time, your code above will actually be expanded to
{
SqlConnection sqlConnection = new SqlConnection(connectionString);
try
{
// .. code
}
finally
{
if (sqlConnection!= null)
((IDisposable)sqlConnection).Dispose();
}
}
You can see how it's a handy shortcut.
Yes. The using statement is just syntactic sugar, and is translated by the compiler into something like
SqlConnection sqlConnection;
try
{
sqlConnection = new SqlConnection(connectionString);
// code...
}
finally
{
if (sqlConnection != null)
sqlConnection.Dispose();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With