0

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.

marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425

2 Answers2

3

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.

LogicalDesk
  • 1,153
  • 4
  • 16
  • 42
1

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.

MakePeaceGreatAgain
  • 33,293
  • 6
  • 51
  • 100