Home
VB.NET
ByVal and ByRef Example
Updated Mar 7, 2024
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.
The ByVal and ByRef keywords change how parameters are received. They can be used to specify exactly how a function uses its arguments.
Function
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.
Integer
Part 1 When the integer value is passed to Example1, its value is only changed inside the Example1 subroutine. In Main the value is unchanged.
Part 2 In 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 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.
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Mar 7, 2024 (edit).
Home
Changes
© 2007-2025 Sam Allen