Export (0) Print
Expand All

Argument Passing ByVal

Visual Studio .NET 2003

If you pass a variable argument by value using the ByVal keyword, the procedure cannot modify the variable itself. However, if the argument is a reference type, you can modify the members of the object to which it points, even though you cannot replace the object itself. In particular, you can modify the members of the object. For example, if the argument is an array variable, you cannot assign a new array to it, but you can change one or more of its elements. The changed elements are reflected in the underlying array variable in the calling code.

The following example shows two subroutines that take an array variable by value and operate on its elements. Increase simply adds one to each element. Replace assigns a new array to the argument array A() and then adds one to each element. However, the reassignment does not affect the underlying array variable in the calling code.

Public Sub Increase(ByVal A() As Long)
   Dim J As Integer
   For J = 0 To UBound(A)
      A(J) = A(J) + 1
   Next J
End Sub
   ' ...
Public Sub Replace(ByVal A() As Long)
   Dim J As Integer
   Dim K() As Long = {100, 200, 300}
   A = K
   For J = 0 To UBound(A)
      A(J) = A(J) + 1
   Next J
End Sub
 ' ...
Dim N() As Long = {10, 20, 30, 40}
Increase(N)
MsgBox("After Increase(N): " & _
              CStr(N(0)) & CStr(N(1)) & CStr(N(2)) & CStr(N(3)))
' The element values of N() are now 11, 21, 31, and 41. Because N is a 
' reference type, Replace could change its members.
Replace(N)
MsgBox("After Replace(N): " & _
              CStr(N(0)) & CStr(N(1)) & CStr(N(2)) & CStr(N(3)))
' The element values of N() are still 11, 21, 31, and 41. Because N was 
' passed ByVal, Replace could not modify the variable N by assigning a 
' new array to it. When Replace created the new array instance K and 
' assigned it to the local variable A, it lost the reference to N() 
' passed in by the calling code. When it changed the members of A(), 
' only the local array K() was affected.

See Also

Argument Passing ByRef | Argument Passing Mechanism | Argument Passing by Position and by Name | ByVal | ByRef

Show:
© 2014 Microsoft