Previous section   Next section

5.8 Destroying Objects

Unlike many other programming languages (C, C++, Pascal, etc.), VB.NET provides garbage collection. Your objects are destroyed when you are done with them. You do not need to worry about cleaning up after your objects unless you use unmanaged resources. An unmanaged resource is an operating system feature outside of the .NET Framework, such as a file handle or a database connection. If you do control an unmanaged resource, you will need to explicitly free that resource when you are done with it. Implicit control over this resource is provided with a Finalize( ) method, which will be called by the garbage collector when your object is destroyed:

  Protected Overrides Sub Finalize( )
    ' release non-managed resources
    MyBase.Finalize( )
  End Sub

The Protected keyword is described in Section 5.1.5 earlier in this chapter. For a discussion of the Overrides and MyBase keywords, see Chapter 6.

It is not legal to call Finalize( ) explicitly. Finalize( ) will be called by the garbage collector. If you do handle precious unmanaged resources (such as file handles) that you want to close and dispose of as quickly as possible, you ought to implement the IDisposable interface. (You will learn more about interfaces in Chapter 8.) The IDisposable interface requires that you create a method named Dispose( ) that will be called by your clients.

If you provide a Dispose( ) method, you should stop the garbage collector from calling your object's destructor. To stop the garbage collector, you call the shared method GC.SuppressFinalize( ), passing in the Me reference for your object. Your Finalize( ) method can then call your Dispose( ) method. Thus, you might write:

Public Class Testing
   Implements IDisposable
   Dim is_disposed As Boolean = False

   Protected Sub Dispose(ByVal disposing As Boolean)
      If Not is_disposed Then
         If disposing Then
            Console.WriteLine("Not in destructor, OK to reference other objects")
         End If
         ' perform cleanup for this object
         Console.WriteLine("Disposing...")
      End If
      Me.is_disposed = True
   End Sub

   Public Sub Dispose( ) Implements IDisposable.Dispose
      Dispose(True)
      'tell the GC not to finalize
      GC.SuppressFinalize(Me)
   End Sub

   Protected Overrides Sub Finalize( )
      Dispose(False)
      Console.WriteLine("In destructor.")
   End Sub

End Class

  Previous section   Next section
Top