You've created an object that allocates its own resources, and you're ready to get rid of it. What's the correct method?
Visual Basic provides three primary methods for getting rid of objects that implement the IDisposable interface:
The constructor for a class may allocate shared resources that need to be properly released as quickly as possible when no longer needed. Some classes implement their own custom method for doing this, such as including a "release all resources" method. You must examine and follow the documented standards for such objects.
Fortunately, most objects that hold such external or shared resources implement the System.IDisposable interface. This interface exposes a standard Dispose() method that your code or other standardized generic components can call to free important resources. You can add IDisposable to your own classes, as follows:
Class SomeClass Implements IDisposable Protected Overridable Sub Dispose( ) _ Implements IDisposable.Dispose ' ----- Add cleanup code here. End Sub End Class
For classes that do not allocate shared or external resources, or where holding on to such resources for a long time will not degrade application or system performance, the standard Finalize() deconstructor may be used to free held resources. For such classes, no special processing is needed to destroy the object. Simply wait for the object to be released on its own, or set it to Nothing.
If you implement IDisposable on a custom class, you should also override the Finalize() method to ensure that resources are freed even if the user of the class forgets to call Dispose():
Protected Overrides Sub Finalize( ) ' ----- Add cleanup guarantee here. End Sub