VB.NET ByVal Versus ByRef Example

Understand the ByVal and ByRef keywords. These keywords describe formal parameters in Functions.

dot net perls

ByVal, ByRef. ByVal and ByRef change how parameters are received. A parameter passed ByVal—by value—can be changed in the new method. Its value will not be changed elsewhere. ByRef, by reference, means the variable location itself is copied.

Example. This program introduces 2 subs other than the Main subroutine. It shows the Example1 method, which receives an integer parameter ByVal, and the Example2 method, which receives an integer ByRef.IntegerSub
ByVal: 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.
ByRef: 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.
VB.NET program that shows ByVal and ByRef Module Module1 Sub Main() Dim value As Integer = 1 ' The integer value doesn't 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 Output 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.

If you access or mutate fields or methods on that 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.

Summary. Understanding the difference between ByVal and ByRef is important. 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.


© 2007-2020 sam allen. send bug reports to info@dotnetperls.com.