Microsoft KB Archive/166928

= FIX: Public Properties of VB4 Class Are Passed by Reference =

Article ID: 166928

Article Last Modified on 6/29/2004

-

APPLIES TO


 * Microsoft Visual Basic 5.0 Control Creation Edition
 * Microsoft Visual Basic 5.0 Learning Edition
 * Microsoft Visual Basic 5.0 Professional Edition
 * Microsoft Visual Basic 5.0 Enterprise Edition
 * Microsoft Visual Basic 4.0 Professional Edition
 * Microsoft Visual Basic 4.0 Enterprise Edition

-



This article was previously published under Q166928



SYMPTOMS
If you have a Visual Basic 4.0 class with a public property implemented like the following: Public MyProp As Integer Visual Basic 4.0 passes the property by reference (ByRef).

However, if your property is implemented in Visual Basic 4.0 using property procedures (Property Get, Property Let, Property Set), it will be passed by value (ByVal).



STATUS
This problem has been fixed in Visual Basic 5.0. All properties are now passed by value (ByVal) for consistency.

In addition, all code internal to the class still has direct access to member variable data: MyClass.CLS =========== Public MyProp As Integer

Public Sub MyMethod MyProp = 5 '// This has direct access to the class data End Sub ===========



MORE INFORMATION
Microsoft has acknowledged that this change in behavior may be an issue for some developers porting Visual Basic 4.0 code to Visual Basic 5.0. Code that relies on the ByRef functionality stated above will need to be modified.

One possible way to modify the Visual Basic 4.0 for porting to Visual Basic 5.0 is shown below:

Original Visual Basic 4.0 code: MyClass.CLS ===========  Public MyProp As Integer ===========

MyBas.BAS =========  Sub Compute(ByRef iTarget As Integer) Dim iTemp as Integer '// implementation code iTarget = iTemp End Sub

Sub Main Dim MyObject As MyClass MyObject.MyProp = 97 Call Compute(MyObject.MyProp) End Sub ========= Modified Sub Main for Visual Basic 5.0: Sub Main Dim MyObject As MyClass Dim iTtemp1 As Integer Dim iTemp2 As Integer MyObject.MyProp = 97 iTemp1 = MyObject.MyProp iTemp2 = iTemp1 Call Compute(iTemp2) If iTemp1 <> iTemp2 Then MyObject.MyProp = iTemp2 iTemp1 = iTemp2 End If  End Sub Exposing public variables is not a recommended programming technique. The following demonstrates possible modifications to MyClass.CLS, illustrating a data-hiding technique to preserve class member data: MyClass.CLS ===========  Private m_MyProp As Integer

Public Property Let MyProp(NewValue As Integer) '// implement validation code and data formatting m_MyProp = NewValue End Property

Public Property Get MyProp As Integer MyProp = m_MyProp End Property

Keywords: kbbug kbfix KB166928

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.