Visual Basic Language Concepts
Using Constructors and Destructors

Constructors and destructors control the creation and destruction of objects.

To create a constructor for a class, create a procedure named Sub New anywhere in the class definition. To create a parameterized constructor, specify the names and data types of arguments to Sub New just as you would specify arguments for any other procedure, as in the following code:

Sub New(ByVal sString As String)

Constructors are frequently overloaded, as in the following code:

Sub New(ByVal sString As String, iInt As Integer)

When you define a class derived from another class, the first line of a constructor must be a call to the constructor of the base class, unless the base class has an accessible constructor that takes no parameters. A call to the base class containing the above constructor, for example, would be MyBase.New(sString). Otherwise, MyBase.New is optional, and the Visual Basic .NET runtime calls it implicitly.

After writing code to call the parent object's constructor, you can add any additional initialization code to the Sub New procedure. Sub New can accept arguments when called as a parameterized constructor. These parameters are passed from the procedure calling the constructor; for example, Dim AnObject As New ThisClass(X).

The following code example shows how to use Dispose and Finalize to release resources:

' Design pattern for a base class.
Public Class Base
    Implements IDisposable
    ' Implement IDisposable.
    Public Overloads Sub Dispose() Implements IDisposable.Dispose
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub

    Protected Overridable Overloads Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            ' Free other state (managed objects).
        End If
        ' Free your own state (unmanaged objects).
        ' Set large fields to null.
    End Sub

    Protected Overrides Sub Finalize()
        ' Simply call Dispose(False).
        Dispose(False)
    End Sub
End Class

' Design pattern for a derived class.
Public Class Derived
    Inherits Base

    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            ' Release managed resources.
        End If
        ' Release unmanaged resources.
        ' Set large fields to null.
        ' Call Dispose on your base class.
        MyBase.Dispose(disposing)
    End Sub
    ' The derived class does not have a Finalize method
    ' or a Dispose method with parameters because it inherits
    ' them from the base class.
End Class

The following example shows a common design pattern for using the Dispose destructor:

Dim con As Connection, rs As RecordSet
Try
   con = New Connection("xyz")
   rs = New RecordSet(con, "MyTable")
   ' Use the connection if successful.
Finally
' Call the Dispose method when done with any created objects.
If Not con Is Nothing Then
      con.Dispose()
   End If
   If Not rs Is Nothing Then
      rs.Dispose()
   End If
End Try

The next example creates an object using a parameterized constructor, and calls destructors when the object is no longer needed:

Sub TestConstructorsAndDestructors()
   Dim X As Integer = 6
   Dim AnObject As New ThisClass(X)
   ' Place statements here that use the object.
   AnObject.DoSomething()
   ' Test the parameterized constructor. 
   MsgBox("The value of ThisProperty after being initialized " & _
          " by the constructor is " & AnObject.ThisProperty)
   ' Run the Dispose method when you are done with the object.
   AnObject.Dispose()
End Sub

   Public Class BaseClass
      Sub New()
         MsgBox("The base class is initializing with Sub New.")
      End Sub

      Protected Overrides Sub Finalize()
         MsgBox("The base class is destroying objects with Sub Finalize.")
         ' Place final cleanup tasks here.
         MyBase.Finalize()
      End Sub
   End Class

   Public Class ThisClass
      Inherits BaseClass
      Implements IDisposable ' Implements the Dispose method of IDisposable.
      Private m_PropertyValue  As Integer

      Sub New(ByVal SomeValue As Integer)
         MyBase.New() ' Call MyBase.New if this is a derived class.
         MsgBox("Sub New is initializing the class ThisClass.")
         ' Place initialization statements here. 
         m_PropertyValue  = SomeValue
      End Sub

      Property ThisProperty() As Integer
         Get
            ThisProperty = m_PropertyValue 
         End Get
         Set(ByVal Value As Integer)
            m_PropertyValue  = Value
         End Set
      End Property

      Sub DoSomething()
         ' Place code here that does some task.
      End Sub

      Protected Overrides Sub Finalize()
         MsgBox("Finalize is destroying objects in ThisClass.")
         ' Place final cleanup tasks here.
         MyBase.Finalize()
      End Sub

      Overridable Sub Dispose() Implements IDisposable.Dispose
         MsgBox("The ThisClass is running Dispose.")
      End Sub
   End Class

When you run this example, the class ThisClass calls the Sub New constructor of the class BaseClass. After the constructor in the base class is finished, the class ThisClass runs the remaining statements in Sub New that initialize a value for the property ThisProperty.

When the class is no longer needed, the Dispose destructor is called in ThisClass.

If you originally created the instance of ThisClass from a form, nothing will seem to happen until you close the form. At that point, the Finalize destructor runs in the class ThisClass and finally in the class BaseClass.

See Also

Object Lifetime: How Objects Are Created and Destroyed | Finalize Methods and Destructors | IDisposable.Dispose Method

Page view tracker