How to implement the Dispose method in a derived class in Visual Basic .NET or in Visual Basic 2005
'Method that is called by Public to ensure TRUE is passed to DisposePublic Overloads Notoverridable Sub Dispose() Dispose( TRUE ) ' Take yourself off of the finalization queue. GC.SuppressFinalize(Me)End Sub'Method that does the actual disposal of resourcesProtected Overloads Overridable Sub Dispose(ByVal disposing As Boolean) 'Clean Up ResourcesEnd Sub
Dispose() is the method that is called when an object is disposed of in the code in which the object was created. This is a Public method, and therefore it can be used when an instance of the class exists. The Dispose() method then calls the Dispose(Boolean) method and passes a value of TRUE. The Dispose(Boolean) method is responsible for cleaning up the resources of the class.
When a class is derived from a base class, only the Dispose(Boolean) method needs to be overridden. All resource-cleanup for the derived class will be performed in this overridden method, and then the Dispose(Boolean) method for the base class is called. The following is a primitive example of the function overriding the base class:
Protected Overloads Overrides Sub Dispose(disposing As Boolean) 'Clean Up Resources MyBase.Dispose( disposing )End Sub
Dispose() is meant as an entry point for public access to the disposal of an object and to ensure that TRUE is passed to the Dispose(Boolean) method. FALSE should be passed only when the Dispose(Boolean) method is called by the runtime or Finalize method. When FALSE is passed, only the unmanaged resources will be disposed. When TRUE is passed, both the managed and unmanaged resources are disposed.
The Visual Studio Development Environment inserts the code to override the Dispose() method into a class that inherits a system object (for example, Inherits System.Windows.Forms.TextBox). This is performed from the menus (at the top of the code window, by default) by selecting Overrides and then clicking Dispose(). The code that is inserted looks something like the following:
Public Overloads Overrides Sub Dispose() 'Clean Up ResourcesEnd Sub
Additional information: Declaration referenced in a method implementation can not be a final method. Type: ClassLibrary1.UserControl1. Assembly: Dispose.
To correct this issue, just overload the Dispose(Boolean) method instead of Dispose(), and make sure that a call is made to the Dispose(Boolean) method of the base class and that TRUE is passed to it.
NOTE: In Visual Basic .NET or in Visual Basic 2005, the Overridable keyword is used like the Virtual keyword in C# and C++. Methods are, by default, NotOverridable.
Article ID: 315528 - Last Review: 05/11/2007 06:00:47 - Revision: 2.6
- kbvs2005swept kbvs2005applies kberrmsg kbinfo KB315528