Tangible Software Solutions

When are ByRef Parameters Required in VB?

Many programmers are confused about when 'ByRef' parameters are required and when they are not required. For value types, 'ByRef' is required when the changed value needs to be seen after the method call.
A value type object is identified by it's value (hence the name 'value type'), so typically they are changed only via a direct assignment to the object, e.g., intParam = 2.

For reference types, confusion abounds. Some people say that reference type parameters never need 'ByRef' since a copy of the object is never passed. But this only means that you can change the internal 'state' of a reference type parameter and have that change be seen after calling the method without using 'ByRef' (e.g., you can add an item to a generic List).
Instead, if you're assigning a new object to the parameter, then the parameter needs to be a 'ByRef' parameter in order to see the new object after the method call.

The following method does not need 'ByRef' for the change to be seen after the method call since the object identity is unchanged, even though the internal state changes — i.e., it's the same object with an item added:

Sub NoByRef(ByVal myList As List(Of Integer))
    myList.Add(2)
End Sub

The following method requires 'ByRef' for the change to be seen after the method call since the object identity itself changes — i.e., the parameter is reassigned to an entirely new object:

Sub NeedsByRef(ByRef myList As List(Of Integer))
    myList = New List(Of Integer)
End Sub

Copyright © 2004 – 2024 Tangible Software Solutions, Inc.