Close() & Dispose(): which one or both?  
Author Message
AlexBB





PostPosted: Visual C# General, Close() & Dispose(): which one or both? Top

In relation to ConnectionString property: shall I Close() it or Dispose() of it or both

More generally for SqlConnection - the same question: what is the proper way

SqlCommand give only a Dispose() option, I guess There is nothing to Close in there, right

Thank you.




Visual C#20  
 
 
Mike Danes





PostPosted: Visual C# General, Close() & Dispose(): which one or both? Top

I don't understand what do you want to do with the ConnectionString property. It's a string, you do not need/cannot Close/Dispose it.

As for the SqlConnection:

Quote from the MSDN docs for SqlConnection.Close():

"

If the SqlConnection goes out of scope, it is not closed. Therefore, unless you have placed your code inside of a using statement, you must explicitly close the connection by calling Close or Dispose. They are functionally equivalent. If the connection pooling value Pooling is set to true or yes, this also releases the physical connection.

"

In general, there is no class that I know of in .NET Framework where Dispose does not do a Close (when Close is available). For example for streams, calling Dispose will also close the stream.

I remember reading somewhere on MSDN (a blog or article) that Close is sort of a "legacy" method and Dispose is the way to go especially since you can use the "using" keyword.


 
 
Vincent Gellera





PostPosted: Visual C# General, Close() & Dispose(): which one or both? Top

Yes. I think no need to close it. Its just a "command" Object where you can put your SQL Statement or set your Stored Procedure and its parameters.

But you can dispose it, it will save you a memory space in RAM.

Good luck!


 
 
AlexBB





PostPosted: Visual C# General, Close() & Dispose(): which one or both? Top

Thank you both, Mike and Vincent.

On the ConnectionString - it was of course a goofy question. I think I meant SqlConnection but I am not sure anymore.



 
 
ahmedilyas





PostPosted: Visual C# General, Close() & Dispose(): which one or both? Top

you maybe best overall, best practice, to enclose any disposable objects in a using() {} block as it will automatically dispose of the object for you.

using (SqlCommand cmd = new SqlCommand(command))

{

...

}