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

See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist