devxlogo

Beware of hidden circular references between a form and an object

Beware of hidden circular references between a form and an object

Many VB developers use a class module to augment the capabilities of a control on a form. For example, consider this simple example, that formats a currency value in a TextBox control when the focus leaves the control:

' ------ the FORM1 moduleDim Formatter As New CFormatterPrivate Sub Form_Load()    ' bind the object to a textbox    Set Formatter.TextBox = Text1End Sub' -------- the CFORMATTER class modulePublic WithEvents TextBox As TextBoxPrivate Sub TextBox_LostFocus()    ' format the value when the focus leaves the control    TextBox.Text = Format(TextBox.Text, "###,##0.00")End Sub

The above code contains an hidden circular reference between the form and the instance of the CFormatter class. The circular reference isn’t apparent at first, because the CFormatter object references the Text1 control, not the form itself. However, because the Text1 control – or any other control for that matter – can exist without its parent form, this creates the circular reference.

This hidden circular reference can cause a memory leak in your application. In fact, when the VB attempts to unloads

devx-admin

Share the Post: