Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is SqlCommand.Dispose() required if associated SqlConnection will be disposed?

I usually use code like this:

using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString)) {    var command = connection.CreateCommand();    command.CommandText = "...";    connection.Open();    command.ExecuteNonQuery(); } 

Will my command automatically disposed? Or not and I have to wrap it into using block? Is it required to dispose SqlCommand?

like image 649
abatishchev Avatar asked Nov 27 '09 10:11

abatishchev


People also ask

Is it necessary to dispose SqlConnection as well as SqlCommand?

yes , it is necessary to dispose the sqlconnection and sqlcommand object after your piece of code gets executed.

Do I need to dispose SqlConnection?

While there may be many instances (like on SqlConnection) where you call Disponse() on some object and it simply calls Close() on it's connection or closes a file handle, it's almost always your best bet to call Dispose()! unless you plan on reusing the object in the very near future.

Does disposing SqlCommand close connection?

Dispose(); The first command was disposed when the using block was exited. The connection was still open and good for the second command. So, disposing of the command definitely does not dispose of the connection it was using.

How do I close SqlCommand?

SqlConnection Class Open() : The open() method is used to open the Database connection. Close() : The close() method is used to close the Database connection.


2 Answers

Just do this:

using(var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString)) using(var command = connection.CreateCommand()) {    command.CommandText = "...";    connection.Open();    command.ExecuteNonQuery(); } 

Not calling dispose on the command won't do anything too bad. However, calling Dispose on it will suppress the call to the finalizer, making calling dispose a performance enhancement.

like image 116
RichardOD Avatar answered Sep 18 '22 15:09

RichardOD


The safest policy is to always call Dispose() on an object if it implements IDisposable, either explicitly or via a using block. There may be cases where it is not required but calling it anyway should never cause problems (if the class is written correctly). Also, you never know when an implementation may change meaning that where the call was previously not required it is now definitely required.

In the example you've given, you can add an extra inner using block for the command, as well as maintaining the outer using block for the connection.

like image 30
Adam Ralph Avatar answered Sep 18 '22 15:09

Adam Ralph