The ByVal modifier indicates that a parameter is passed to a procedure or function by value. In Visual Basic, ByVal is used by default and guarantees that changes made to the parameter within the procedure do not affect the original variable passed by the caller.
In classic versions of VB, any parameter could be passed in two ways: by value or by reference. With the development of the language and the emergence of complex data types (structures, classes), the importance of a conscious choice between ByVal and ByRef has increased.
Incorrect choice of parameter passing method often leads to errors: one can unintentionally change the variable in the calling code, or conversely — expect changes that will not occur.
ByVal is used when the procedure needs to work with a copy of the value. It is applied for passing primitive types, structures, and sometimes even reference types, if it is important to maintain the reference.
Code example:
Sub Increment(ByVal number As Integer) number += 1 End Sub Dim myValue As Integer = 10 Increment(myValue) Console.WriteLine(myValue) ' Returns 10, not 11
Key features:
How will an object (for example, an instance of a class) behave if passed with the ByVal modifier?
Answer: A copy of the reference to the object is passed, not the object itself. You can change the fields of the object from the procedure — changes will be visible outside. The reference, not the object, cannot be replaced with a new one inside the procedure with an effect for the calling code.
Code example:
Class Counters Public Value As Integer End Class Sub ModifyCounter(ByVal c As Counters) c.Value = 999 ' Changes the property! c = New Counters() ' This change is not visible to the calling code End Sub Dim example As New Counters() ModifyCounter(example) Console.WriteLine(example.Value) ' Outputs 999
Will the value of a structure change when passed ByVal if its fields are modified inside the procedure?
Answer: No, the entire instance of the structure is copied, and changes do not propagate outside. Each record of a structure, for example, Point, in the procedure is its own.
Is it necessary to explicitly specify ByVal for a parameter?
Answer: No, ByVal is used by default, and explicit specification is only for greater readability and adherence to coding style.
A developer passes an array ByVal to a function, expecting that elements can be added to the array and a new array will appear for the caller (de-facto Reference Type is passed by reference).
Pros:
Cons:
ByVal is used for passing an index of an array that should not be changed by the function. Even if the index value is changed inside, the original variable is untouched.
Pros:
Cons: