using statement and SqlClient

Gavin

New member
Joined
Aug 12, 2008
Messages
2
Programming Experience
5-10
I am unsure about whether to use Using around sqlclient objects, for example the sqlconnection or sqlcommand objects. Both implement IDispose and make use of unmanaged resources but are themselves managed. So should I use Using or just allow them to go out of scope and rely on the GC?
 
Always call Dispose method when a class expose this (in code instance context), Using is just a shortcut for Try-Catch-Dispose. Some classes may have a Close method that may be used interchangeably when documentation says so, an example is the SqlConnection:
MSDN said:
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.
 
Thank you for your reply.
From your reply I would infer that IDispose is implemented something like this then (following the suggested pattern for its implementation):

Protected Overridable Sub Dispose(ByVal disposing As Boolean)
If Not Me.disposedValue Then
If disposing Then
Me.Close()
End If

' TODO: free your own state (unmanaged objects).
' TODO: set large fields to null.
End If
Me.disposedValue = True
End Sub
 
Back
Top