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:
To see what the ByVal keyword does, add a line that changes the value of the argument in the function:
Now call the function as follows:
If you enter the value 32, the following message is displayed:
Replace the ByVal keyword with the ByRef keyword in the function's definition and call the function as follows:
This time the program displays the following message:
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|