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, ...

Get Programming Visual Basic .NET, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.