1

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
  • 732,580
  • 175
  • 1,330
  • 1,459

2 Answers2

4

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,237
  • 4
  • 16
  • 46
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
  • 35,491
  • 6
  • 60
  • 111