ByVal
, ByRef
In VB.NET a parameter passed ByVal
—by value—can be changed in the new method. Its value will not be changed elsewhere. ByRef
means the variable location itself is copied.
The ByVal
and ByRef
keywords change how parameters are received. They can be used to specify exactly how a function uses its arguments.
This program introduces 2 subs other than Main
. It shows the Example1
method, which receives an integer parameter ByVal
, and the Example2
method, which receives an integer ByRef
.
Example1
, its value is only changed inside the Example1
subroutine. In Main
the value is unchanged.Example2
, the reference to the integer is copied, so when the value is changed, it is reflected in the Main
sub.Module Module1 Sub Main() Dim value As Integer = 1 ' Part 1: the integer value does not change here when passed ByVal. Example1(value) Console.WriteLine(value) ' Part 2: the integer value does change when passed ByRef. Example2(value) Console.WriteLine(value) End Sub Sub Example1(ByVal test As Integer) test = 10 End Sub Sub Example2(ByRef test As Integer) test = 10 End Sub End Module1 10
The program here used Integers, which are a value type. With object references, you are dealing with a value that indicates a memory location.
ByVal
, you are copying the bytes in that reference—not the actual data pointed to by the reference.If you access or mutate fields or methods on a copied reference, the changes will be reflected everywhere in the program.
ByVal
is often useful for references and also values. ByRef
is typically more useful for values because you more often need to change the original values.