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.