Visual Basic .NET/IDisposable

From Wikibooks, open books for an open world
Jump to navigation Jump to search

The IDisposable Interface

Basics

The IDisposable interface is implemented when an object needs to be "cleaned up" after use. If an object has a "Dispose" method, then it needs to be cleaned up after use.

The easiest way to clean up this sort of object is by using the VB keyword "Using".

    Using f As New Form
        f.Show
    End Using

When an IDisposable object is a form-level variable, it should be disposed in the Form_Closed event.

    Public Class Form1
        Private mfrmChild As Form
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            mfrmChild = New Form
            mfrmChild.Text = "Child"
            mfrmChild.Show()
        End Sub
        Private Sub frmMain_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
            mfrmChild.Dispose()
        End Sub
    End Class