First: 1
Second: 1
<% ' This sub look like it just swaps the values ' in the two variables, but does it? Sub SwapValues(ByVal iFirst, ByRef iSecond) Dim iTemp iTemp = iFirst iFirst = iSecond iSecond = iTemp End Sub ' Declare two vars and set their initial values. Dim iFirst, iSecond iFirst = 1 iSecond = 2 ' Call our Sub. SwapValues iFirst, iSecond ' Both values are now 1! ' ' iSecond was changed because it was passed ByRef ' while iFirst was not since it was passed ByVal. ' ' Don't believe me? ...see for yourself: Response.Write "<p>First: " & iFirst & "</p>" Response.Write "<p>Second: " & iSecond & "</p>" ' In order to actually swap the values you'd need ' to make both parameters ByRef. %>
ByVal Versus ByRef
ByVal stands for By Value. This means that a variable will maintain its value even if it’s changed inside a sub procedure. When a variable is passed by value, two memory locations are involved. The second memory location is accessed when the sub is called. At this time, the second memory location holds the value passed into the sub. After the sub has finished executing, the second memory location is released and the value is lost.
If you pass a variable ByRef, By Reference, any changes will remain in effect after the sub is called. Only one memory location is involved. Only variables can be passed ByRef. Literals cannot.
To sum it up, by default VB.NET arguments are passed by value. A copy is sent to the subprocedure or function rather than a pointer to the original memory location. Any changes made to the arguments inside of the sub will NOT affect the variables passed to the sub. When you choose to pass by reference, you are passing in the original memory location. Any changes made to the arguments inside of the sub will affect the variables passed to the sub.
Public Sub AddNumbers(ByVal NumOne As Integer, ByVal NumTwo As Integer)
NumOne = NumOne + 20
NumTwo = NumTwo + 20
MsgBox("Inside the sub the sum is: " & (NumOne + NumTwo),
_ MsgBoxStyle.Information, "Passing By Value")
End Sub
Private Sub Form1_Load(ByVal sender As System.Object,_
ByVal e As System.EventArgs) Handles MyBase.Load
Dim Number1 As Integer = 32
Dim Number2 As Integer = 11
AddNumbers(Number1, Number2)
MsgBox("Outside the sub the sum is: " & (Number1 + Number2), _
MsgBoxStyle.Information, "Passing By Value")
End Sub