If I lose the reference to an object that contains an open connection to the database, is the connection closed when the GC cleans up my object (i.e by the destructor of the SqlConnection class
)?
Or is it causing connection leak?
It is closed in Dispose
not in the destructor(Finalize
). So use the using
-statement and you're on the safe side.
It was hard to find documentation (don't rely on decompiled assemblies) but finally i found it in SqlConnection.Close
:
If the SqlConnection goes out of scope, it won't be closed. Therefore, you must explicitly close the connection by calling Close or Dispose. Close and Dispose are functionally equivalent.
....
The following example creates a SqlConnection, opens it, displays some of its properties. The connection is automatically closed at the end of the using block.
Furthermore:
Caution
Do not call Close or Dispose on a Connection, a DataReader, or any other managed object in the Finalize method of your class. In a finalizer, you should only release unmanaged resources that your class owns directly. If your class does not own any unmanaged resources, do not include a Finalize method in your class definition.
The source (ILSpy, .NET 4):
// System.Data.SqlClient.SqlConnection
protected override void Dispose(bool disposing)
{
if (disposing)
{
this._userConnectionOptions = null;
this._poolGroup = null;
this.Close(); // <-------
}
this.DisposeMe(disposing);
base.Dispose(disposing);
}