JavaScript Editor JavaScript Editor     JavaScript Debugger

Previous Section Next Section

Main Page

Using the Finalize Method (Creating Destructors)

We know how to create constructors, but what about destructors, which are run when an object is destroyed? You can place code to clean up after the object, such saving state information and closing files, in a destructor. In Visual Basic, you can use the Finalize method for this purpose. The Finalize method is called automatically when the .NET runtime determines that the object is no longer needed.

Here's a quick example, named Finalize on the CD-ROM. In this case, I'm creating an object of a class named Class1, and adding a Finalize method that beeps when the object is destroyed. Here's what the code looks like:

Public Class Form1
    Inherits System.Windows.Forms.Form

    'Windows Form Designer generated code

    Dim Object1 As New Class1()
End Class

Public Class Class1
    Protected Overrides Sub Finalize()
    End Sub
End Class

Note that you have to use the Overrides keyword with Finalize, because you're actually overriding the Finalize method built into the Object class. When you run this example, a blank form appears and an object, Object1, of Class1 is created; when you close the form, Object1 is destroyed and the Beep method beeps. The usual code you place in Finalize is a little more substantial, of course, and you can use this method to deallocate resources, disconnect from the Internet, inform other objects that the current object is going to be destroyed, and more.

Previous Section Next Section

JavaScript Editor Free JavaScript Editor     JavaScript Editor