Let's say I have the following function:
Function myFunction(j As Integer) As Double
myFunction = 3.87 * j
Exit Function
End Function
Is j
passed as value ByVal
or by reference ByRef
?
Or does it depends of the data type? What if I have a complex object passed as the value?
Thanks in advance!
j
in this case is passed ByVal
. A parameter is always passed ByVal
unless ByRef
is explicitly stated. From section 9.2.5 of the VB.NET 10 Specification:
A parameter that does not specify ByRef or ByVal defaults to ByVal.
Parameters are passed ByVal
unless explicitly specified. For details, see Passing Arguments by Value and by Reference, which states:
The default in Visual Basic is to pass arguments by value. You can make your code easier to read by using the ByVal keyword. It is good programming practice to include either the ByVal or ByRef keyword with every declared parameter.
As for:
What if I have a complex object passed as the value?
This is fine, provided the "complex object" is a class (Reference type), you're not going to be doing a lot of copying. This is because the reference to the object instance is passed by value (ByVal), which means you're only copying a single reference, even if the class is very large.
If, however, the complex object is a structure (value type), you will be causing the object to be copied when the method is called. This, btw, is why some frameworks like XNA provide alternative versions of many methods (like Matrix.Multiply) that have an option to pass ByRef
- this avoids the expensive copies of the Matrix structures.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With