Today, I was just looking at the IL of SqlConnection
class, so I found few things which are interesting to me and hopefully to you as well.
SqlConnection.Dispose()
shall call Close()
method internally, so if you’re using Using(){}
block to open a connection, then you need not Close
it explicitly. SqlConnection.Dispose()
method also calls SqlConnection.DisposeMe(bool)
method internally, although SqlConnection.DisposeMe(bool)
method is empty, but this method is private
to this class. The reason I guess they have done this way is for futuristic purposes.
There are quite a few differences I could spot out in the IL with respect to Dipose()
and Close()
methods:
Close()
method is actually an abstract
method in DBConnection
class. It is overridden and made virtual
in SqlConnection
class, which gives the consumer code more flexibility in customizing the Close
operation if at all needed. - There is no
Dispose()
method in DBConnection
class but instead it's a virtual
method in SqlConnection
class. Close()
method actually only closes the connection object via Native interface with the DB and tries to clean it up. Internally, it uses DBConnectionInternal.CloseConnection
method to actually close the transaction with the DB by using many APIs. - On the other hand,
Dispose()
method will not close any connection explicitly, but calls Close()
method. Along with it, it also calls DisposeMe()
method internally.
Happy coding!
P.S: Your comments/votes are much appreciated.