Passing Variables By Value or Reference

Odd Effects of Passing Arguments

Now how would this possibly affect our passing values between functions. Assume for a moment that we try to pass a value ByRef between two statements. We pass the memory allocation address to the next statement, and the statement will then attempt to access the data in its memory location.

If the data type is not of the same type as the one requested by the called statement, you would receive an error at compile time already. This is very good to know, as this means you will minimize the risk of sending a bug out to the end users.

However, sending the same variable to the same statement, using ByVal has a different result. Assume you are sending the Integer value 1024 to a statement requiring a ByVal MyLong As Long. This would result in a copy of the value 1024 being sent to the statement.

It would also approve of the value it self, as it fits within a Long.

Integers hold 2 bytes of memory and range between -32,768 to 32,767 while Long or also referred to as "long integers" hold 4 bytes of memory space and range between -2,147,483,648 to 2,147,483,647.

So in other words, somewhere in the depth of the language, there is a check from the compiler to see that the correct Variable Type is being passed internally as well.

One way to avoid this data type verification is to pass a ByRef value as an expression instead of assigning a variable type to the value. Visual Basic evaluates the expression and will attempt to pass the result of the expression if it can.

The simplest way to pass a variable as an expression is simply to enclose it in parenthesis.

For example Call MyFunction(AnInteger)

Function MyFunction(ByRef TheString As String)
MsgBox "The string is " & TheString
End Function

You might also like...

Comments

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Debugging is anticipated with distaste, performed with reluctance, and bragged about forever.” - Dan Kaminsky