devxlogo

Passing Public class variables by reference

Passing Public class variables by reference

Under VB4 Public variables in form and class modules were implemented in the same manner as variables in BAS modules, that is, as direct references to memory locations. This allowed VB programmers to create procedures that modified values passed by reference, as in:

'--- the CInvoice class -----Public Number As Integer'---- elsewhere in the applicationDim p As New CInvoiceIncrement p.Number     ' this worksPrint p.Number         ' displays "1"Sub Increment(value As Long)    value = value + 1End Sub

Under VB5 and VB6, Public variables in FRM, CLS and all other types of class modules (that is, all types of VB modules but BAS modules) are internally implemented as a pair of hidden Property Get and Property Let procedures. This means that, when such Public variables are passed as arguments of a procedure, what is actually passed is the return value of a procedure call. Hence, even if the Public property is passed with ByRef, the called procedure acts on a copy of its value, and therefore can’t modify the value of the property.

This modified behavior fixes a problem of VB4, which didn’t enforce a strict encapsulation of properties implemented as Public variables. However, when porting a program from VB4 to VB5 or VB6 you should pay attention to this issue, because the code might not work any longer. The only workaround is to move the property’s value into a temporary variable, and pass such a temporary variable instead, as in:

Dim temp As Longtemp = p.NumberIncrement tempp.Number = temp

There are two other details to be aware of:

  • When the Public variable is passed to the external procedure from inside the class module, it is passed by reference, and therefore the procedure can change its value. In other words:

    ' inside the CInvoice class moduleIncrement Number    ' it works!

  • On the other hand, if you use the Me prefix from inside the class module, the code will access the external property, and therefore the hidden property procedures. In other words:

    ' inside the CInvoice class moduleIncrement Me.Number    ' it doesn't work!

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