Visual Basic.NET 2008 > Programming Fundamentals

By Value versus by Reference - Argument-Parsing Mechanism in VB.NET 2008

When you pass an argument by value, the procedure sees only a copy of the argument. Even if the procedure changes it, the changes aren't permanent; in other words, the value of the original variable passed to the procedure isn't affected. The benefit of passing arguments by value is that the argument values are isolated from the procedure, and only the code segment in which they are declared can change their values. This is the default argument-passing mechanism in Visual Basic 2008.

In VB 6, the default argument-passing mechanism was by reference, and this is something you should be aware of, especially if you're migrating VB 6 code to VB 2008.

To specify the arguments that will be passed by value, use the ByVal keyword in front of the argument's name. If you omit the ByVal keyword, the editor will insert it automatically because it's the default option. To declare that the Degrees() function's argument is passed by value, use the ByVal keyword in the argument's declaration as follows:

Function Degrees(ByVal Celsius as Single) As Single
Return((9 / 5) * Celsius + 32)
End Function

To see what the ByVal keyword does, add a line that changes the value of the argument in the function:

Function Degrees(ByVal Celsius as Single) As Single
Return((9 / 5) * Celsius + 32)
Celsius = 0
End Function

Now call the function as follows:

CTemp = InputBox("Enter temperature in degrees Celsius")
MsgBox(CTemp.ToString & " degrees Celsius are " & _
Degrees((CTemp)) & " degrees Fahrenheit")

If you enter the value 32, the following message is displayed:

32 degrees Celsius are 89.6 degrees Fahrenheit

Replace the ByVal keyword with the ByRef keyword in the function's definition and call the function as follows:

Celsius = 32.0
FTemp = Degrees(Celsius)
MsgBox(Celsius.ToString & " degrees Celsius are " & FTemp & _
" degrees Fahrenheit")

This time the program displays the following message:

0 degrees Celsius are 89.6 degrees Fahrenheit

When the Celsius argument was passed to the Degrees() function, its value was 32. But the function changed its value, and upon return it was 0. Because the argument was passed by reference, any changes made by the procedure affected the variable permanently. As a result, when the calling program attempted to use it, the variable had a different value than expected.

Table of Contents

     
 
W3computing.com Copyright 2011 © All Rights Reserved
 
  Home | Useful links | Contact us