Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are parameters passed to VB functions by default

Tags:

vb.net

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!

like image 944
Luis Avatar asked May 22 '12 19:05

Luis


2 Answers

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.

like image 28
vcsjones Avatar answered Sep 19 '22 15:09

vcsjones


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.

like image 157
Reed Copsey Avatar answered Sep 21 '22 15:09

Reed Copsey