Skip to content

Some Follow-Up Regarding ByRef

A reader asked me to clarify something about my previous post. Their question was:

When MyMethod is written as:

Sub MyMethod( i() as integer )
  i = array(10,20,30)
  system.debuglog CurrentMethodName + " i(0) = " + str(i(0)) + " i(1) = " + str(i(1)) + " i(2) = " + str(i(2))
End Sub

What happens if instead of trying to assign a new array you just alter the values in the array passed in?

They are asking what happens if MyMethod is written as follows:

Sub MyMethod( i() as integer )
  i(0) = 10
  i(1) = 20
  i(2) = 30
  system.debuglog CurrentMethodName + " i(0) = " + str(i(0)) + " i(1) = " + str(i(1)) + " i(2) = " + str(i(2))
End Sub

Are the contents of the array altered when you get back to the calling method?
To test this, in a new desktop project we have:

Dim i() As Integer
i = Array(1,2,3)
System.debuglog CurrentMethodName + " i(0) = " + Str(i(0)) + " i(1) = " + Str(i(1)) + " i(2) = " + Str(i(2))
MyMethod(i)
System.debuglog CurrentMethodName + " i(0) = " + Str(i(0)) + " i(1) = " + Str(i(1)) + " i(2) = " + Str(i(2))

and run this code we see something like:

9:46:13 AM : My Application Launched
             Window1.Open i(0) = 1 i(1) = 2 i(2) = 3
             Window1.MyMethod i(0) = 10 i(1) = 20 i(2) = 30
             Window1.Open i(0) = 10 i(1) = 20 i(2) = 30

And indeed the values changed do remain when we get back to the caller. Why is this the case? We didn’t use ByRef and still could alter the array?

Recall that ByRef is needed when you want to change the instance referred to. And in this case that isn’t what we’re doing. We’re altering the contents, but not the instance itself. We’re not replacing the entire array with a new one.

This works with classes as well. If you pass an instance in you can alter that instance’ properties based on normal scope rules.

The moral of the story – ByRef is used when you want to alter the actual item. When its a value type like an integer this alters the value it holds. When its a reference type this would allow you to assign a new instance.