IT SOLUTIONS
Your full service technology partner! 
-Collapse +Expand
VB.Net
Search VB.Net Group:

Advanced
-Collapse +Expand VB.Net To/From
To/FromCODEGuides
-Collapse +Expand VB.Net Store
PRESTWOODSTORE

Prestwood eMagazine

September Edition
Subscribe now! It's Free!
Enter your email:

   ► KBProgrammingVB.NetOOP   Print This     
  From the March 2016 Issue of Prestwood eMag
 
VB.Net OOP:
VB.Net Finalizer (Finalize())
 
Posted 15 years ago on 1/18/2009
VB.Net Code Snippet:
 A flashcard from our VB.Net Flashcards Library
 A code snippet from our VB.Net Code Snippets Page

KB101835

General Info: Class Destructor

A special class method called when an object instance of a class is destroyed. With some languages they are called when the object instance goes out of scope, with some languages you specifically have to call the destructor in code to destroy the object, and others use a garbage collector to dispose of object instances at specific times.

Desctructors are commonly used to free the object instance but with languages that have a garbage collector object instances are disposed of when appropriate. Either way, destructors or their equivalent are commonly used to free up resources allocated in the class constructor.

Languages Focus: Destructor

Are object instances freed with a garbage collector? Or, do you have to destroy object instances.

VB.Net Finalizer

In VB.Net you cannot explicitly destroy a managed�object. Instead, the .Net Framework's garbage collector (GC) takes care of destroying all objects. The GC destroys the objects only when necessary. Some situations of necessity are when memory is exhausted or you explicitly call the System.GC.Collect() method. In general, you never need to call System.GC.Collect().

In .Net, a finalizer is used to free non-managed objects such as a file or network resource. In VB.Net, a finalizer is an overridden sub called Finalize. Because you don't know when the garbage collector will call your finalizer, Microsoft recommends you implement the IDisposable interface for non-managed resources and call it's Dispose() method at the appropriate time.

Syntax Example:
Class Cyborg
� Protected Overrides Sub Finalize()
��� 'Free non-managed resources here.
��� MyBase.Finalize()
� End Sub
End Class

Working WinForms Example

The following demonstrates using a finalizer and System.GC.Collect(). I placed a MessageBox.Show() in the finalizer so you can see when it is called. The finalizer gets called when the compiler needs to free resources. You'll notice that although the local variable in the button click event falls out of scope, your finalizer is not called until either you close the form or click the button that calls System.GC.Collect().

Create a form with two buttons and add code as follows:

Public Class Form1
  Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    'Create and use object instance.
    Dim MyRobot2 As New Cyborg("Cameron")
    MessageBox.Show("My robot's name is " & MyRobot2.CyborgName & ".")
  End Sub
 
  Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    'Explicitly call garbage collector (never required for managed code).
    System.GC.Collect()
  End Sub
End Class
  
Public Class Cyborg
  Public CyborgName As String
    
  'Constructor.
  Public Sub New(ByVal pName As String)
    CyborgName = pName
  End Sub
  
  'Destructor/finalizer.
  Protected Overrides Sub Finalize()
    MessageBox.Show("Free non-managed resources here.")
    MyBase.Finalize()
  End Sub
End Class

Cannot Call Finalize()

Although an Object.Finalize() method is implicitly created even when you do not create a finalizer, you still cannot call it directly. In button1_click, if you try to call MyRobot2.Finalize(), it fails the following error.

Error 1 Overload resolution failed because no 'Finalize' is accessible.

Q. If I implement IDisposable, can I also let the garbage collector free my objects?

A. It depends on how you implemented IDisposable and how you are using resources. In general, if you implement IDisposable you should take ownership of calling Dispose for each object instance you create. However, in the simple Working IDisposable Example in this article, you can either call Dispose to free the objects or let the garbage collector free them as demonstrated by the button click events.

Q. If I consume an object that implements IDisposable, should I always call Dispose?

A. In general, yes if it's a shared resource. However, again it depends on why IDisposable was implemented. If Dispose is freeing a resource that may be needed, like a file handle, then yes. There may be exceptions to this rule, but if an object implements IDisposable and the resource is a shared resource, then yes when you create an object instance, you should take ownership and also call Dispose at the appropriate time.

More Info

Definition:  Class Destructor

Comments

1 Comments.
Share a thought or comment...
Comment 1 of 1

Very useful information. I am pretty sure that a lot of people will benefit from it. Thanks for sharing it.

https://www.premiumdissertation.co.uk/

Posted 45 months ago
 
Write a Comment...
...
Sign in...

If you are a member, Sign In. Or, you can Create a Free account now.


Anonymous Post (text-only, no HTML):

Enter your name and security key.

Your Name:
Security key = P177A1
Enter key:
Code Contributed By Mike Prestwood:

Mike Prestwood is a drummer, an author, and creator of the PrestwoodBoards online community. He is the President & CEO of Prestwood IT Solutions. Prestwood IT provides Coding, Website, and Computer Tech services. Mike has authored 6 computer books and over 1,200 articles. As a drummer, he maintains play-drums.com and has authored 3 drum books. If you have a project you wish to discuss with Mike, you can send him a private message through his PrestwoodBoards home page or call him 9AM to 4PM PST at 916-726-5675 x205.

Visit Profile


Linked Certification Question(s)

The following are practice certification questions with answers highlighted. These questions were prepared by Mike Prestwood and are intended to stress an important aspect of this KB post. All our practice questions are intended to prepare you generally for passing any certification test as well as prepare you for professional work.

Advanced

1 Advanced Level Question

Question #1: Multiple Choice

Given the following code snippet:

Public Class Cyborg
End Class
Answer:
1. 

The finalizer method name must be ~Cyborg.

2. 

The finalizer method name can be any method name of your choosing so long as you use the finalizer keyword to indicate this is the finalizer method.

3. 

The finalizer method name must be Destroy.

4. 

The finalizer method name must be Finalize.

5. 

The finalizer method name must be Class_Terminate.


 KB Article #101835 Counter
23309
Since 1/18/2009
Go ahead!   Use Us! Call: 916-726-5675  Or visit our new sales site: 
www.prestwood.com


©1995-2024 Prestwood IT Solutions.   [Security & Privacy]