VB.NET 1.1 Tutorial - The Dispose Method


The Dispose method is used for all tasks associated with freeing resources held by an object, or preparing an object for reuse.

This is useful when dealing with graphics resources as these can slow the system down quickly if the memory is not freed up once finished with. For example when using brushes and fonts, the correct usage of Dispose can be seen in the following code snippet:

Private Sub HelloPaint_Paint( ByVal sender As Object, _
                              ByVal e As PaintEventArgs) _
                              Handles MyBase.Paint

  ' Get Graphics Object
  Dim g As Graphics = e.Graphics

  ' Create Font
  Dim myFont As New Font( "Verdana", 20 )

  ' Create Brush
  Dim myBrush As New SolidBrush( Color.Tomato )

  ' Draw the String
  g.DrawString( "Hello Mum!", myFont, myBrush, 40, 40 )

  ' Now tidy up
  myFont.Dispose()
  myBrush.Dispose()
End Sub

References

For more information on the Dispose method, visit MSDN at microsoft here.

What Next?

Return to the Tutorial Contents.