I have disposed of my SqlConnection
this way:
sqlcon.open();
sqlcom.ExecuteNonQuery();
sqlcom.close();
but I am not satisfied with this way of disposing it.
The using
will take care of it for you. Under the hood, SqlConnection.Dispose()
calls the SqlConnection.Close()
method, and SqlCommand.Dispose()
calls SqlCommand.Close()
.
As additional background, a using statement
is syntactic sugar for a try ... finally
that disposes the IDisposable
object in the finally
.
What exactly makes you feel unsatisified? Everthing in your code is fine, except the fact that you could put it into a using-statement to ensure it gets disposed even on an error - e.g. an exception:
using (var sqlconn = new ...)
using (var sqlcom = new ...)
{
sqlcon.open();
sqlcom.ExecuteNonQuery();
}
This way Dispose
(which automatically calls Close
) is called when leaving the using
, be it in a usual way or by an exception.