I wanted to make a helper class for my MySql wrapper. The idea is that the methods that encapsulate mysql command construction and execution have an optional MySqlConnection as an argument. If a specific connection is passed, it uses that, if not, it creates one and disposes of it once done. To save 4 lines off every method, I could use this class in the using block and pass the optional argument as a construction parameter. Anyway, heres the class:
Public Class DynaConnection
Implements IDisposable
Public Dynamic As Boolean
Public Connection As MySqlConnection
Public Sub New(Connection As MySqlConnection)
If Connection Is Nothing Then
Dynamic = True
Me.Connection = Connect()
Else
Dynamic = False
End If
End Sub
Public Shared Widening Operator CType(ByVal Connection As DynaConnection) As MySqlConnection
Return Connection.Connection
End Operator
Public Sub Dispose() Implements IDisposable.Dispose
If Dynamic Then
Connection.Close()
Connection.Dispose()
End If
GC.SuppressFinalize(Me)
End Sub
End Class
When I first wrote the letters "Implements IDisposable" though, a whole wall of code jumped into the class. I looked at msdn to see whats what but over there was an even longer bunch of code on how to "properly" implement IDisposable.
From what I remember from writing simple IDisposable classes before, what I've done in the class above should suffice. Has something changed?
When I first wrote the letters "Implements IDisposable" though, a whole wall of code jumped into the class- yes, that wall of code is the correct way to implement the IDisposable pattern in VB.NET. Keep this (very very little) wall of code. It has two comments in it - "dispose this kind of objects here" and "dispose that kind of objects here". Put your calls to Dispose in these designated places.