ByVal and ByRef Example
This page was last reviewed on Nov 25, 2023.
Dot Net Perls
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.
Keyword notes. ByVal and ByRef 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.
Detail When the integer value is passed to Example1, its value is only changed inside the Example1 subroutine. In Main the value is unchanged.
Note ByVal passes a copy of the bytes of the variable (the value of it). It does not copy a storage location.
Detail In Example2, the reference to the integer is copied, so when the value is changed, it is reflected in the Main sub.
Finally The value is changed to 10 in the Main subroutine after Example2 returns.
Module Module1 Sub Main() Dim value As Integer = 1 ' The integer value does not change here when passed ByVal. Example1(value) Console.WriteLine(value) ' 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 Module
1 10
Objects. The program here used Integers, which are a value type. With object references, you are dealing with a value that indicates a memory location.
So If you pass an object ByVal, you are copying the bytes in that reference—not the actual data pointed to by the reference.
Notes, continued. If you access or mutate fields or methods on a copied reference, the changes will be reflected everywhere in the program.
But If you reassign the reference itself, it will not be reflected in the calling location.
A summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 25, 2023 (edit).
© 2007-2024 Sam Allen.