Previous | Index | Next 

[INFO] VB.NET property values passed to a ByRef parameter can be modified

Note: this article only applies to conversions to VB.NET.

Under VB6, passing a writable property is equivalent to passing the value returned by a method - more precisely, the property’s getter method -, therefore if you pass the value of a property to a ByRef argument the called method receives a copy of the property value; if the method modifies the parameter’s value, the new value isn’t assigned to the property.

Under the same circumstances, however, VB.NET does modify the property when the method exits. This detail can lead to various issues when the VB6 code is migrated, from minor behavioral differences to runtime errors. Consider the following VB6 code:

 
        Sub Form_Load()
            LogAction "Load form", Me.Caption
        End Sub

        Sub LogAction(action As String, detail As String)
            detail = UCase(detail)
            Debug.Print action & ": " & detail
        End Sub

This code works as intended under VB6, but the converted VB.NET code mistakenly converts the form’s caption to uppercase, because it is a writable property passed to a ByRef parameter and the parameter is modified inside the LogAction method. This issue is quite common, because ByRef is the default parameter passing mechanism under VB6 and lazy developers tend to omit the explicit ByVal keyword that would be more appropriate here.

There are two ways to fix this problem, but VB Migration Partner can’t apply these fixes automatically. By far, the most frequent case is parameters that use the by-reference semantics only because the VB6 developer omitted the ByVal keyword in the parameter’s definition: in such cases, adding the ByVal keyword before the migration solves the problem.

 
        Sub LogAction(action As String, ByVal detail As String)
            detail = UCase(detail)
            Debug.Print action & ": " & detail
        End Sub

If the method does require by-reference semantics, you must ensure that you pass the method a copy of the property’s value rather than the value itself. You can do this by enclosing between parenthesis the value being passed to the method:

 
        Sub Form_Load()
            LogAction "Load form", (Me.Caption)
        End Sub

 

Previous | Index | Next