How parameters are passed to VB functions by default

Let's say I have the following function:

Function myFunction(j As Integer) As Double myFunction = 3.87 * j Exit Function End Function 

Passed j as ByVal value or ByRef reference?

Or does it depend on the data type? What if I have a complex object passed as a value?

Thanks in advance!

+4
source share
2 answers

Parameters are passed to ByVal unless explicitly specified. For more details, see Passing Arguments by Value and by Reference , which states:

By default, in Visual Basic, you must pass arguments by value. You can make code easier to read with the ByVal keyword. Good programming practice includes either the ByVal keyword or ByRef with each parameter declared.

Concerning:

What if I have a complex object passed as a value?

This is great if the โ€œcomplex objectโ€ is a class (link type), you are not going to copy a lot. This is because the reference to the instance of the object is passed by value (ByVal), which means that you copy only one link, even if the class is very large.

If, however, the complex object is a structure (value type), you will force the object to be copied when the method is called. This is due to the fact that some structures, such as XNA, provide alternative versions of many methods (for example, Matrix.Multiply ) that can transmit ByRef - this avoids costly copies of matrix structures.

+8
source

j in this case passed ByVal . The parameter is always passed ByVal unless ByRef explicitly specified. From section 9.2.5 VB.NET 10 Specification :

A parameter that ByRef or ByVal does not specify is ByVal by default.

+1
source

Source: https://habr.com/ru/post/1413831/


All Articles