tisdag 5 augusti 2008

What is ByVal & ByRef ?

Aha, now I get it.
ByVal allows a variable value to pass in but not out - in the same name.
In the example below. X comes in to Sub Add2 as 2 and is used inside as 2 (X=X+2). X= 2+2 = 4, but X never leaves Add2 as 4. I came to think of it. If you don't use ByVal you could accidentally change the same variable outside. It is quite likely you have several Sub's running, with the same variable names (i, x, ...).


Post
ByVal means To Pass By Value, meaning you you pass something ByVal you are passing the Value of the Variable not a Pointer to the Variable itself, ie.

Code:

Private Sub Command1_Click()
Dim iTemp As Integer
iTemp = 2
Call Add2(iTemp)
Debug.Print iTemp
End Sub

Private Sub Add2(ByVal X As Integer)
X = X + 2
End Sub


Calling this code would always Print "2" in the Debug Window.If you modify the Add2 Routine to be ByReference, it would Print "4".


Article
Did you know that you can pass a parameter to a Sub or Function in two different ways? You can either do it ByVal (By Value) or ByRef (By Reference). So what's the difference?
Well when you pass a variable ByVal a new instance of the variable is created and given to the routine being called. Any changes made to the value of this variable have no effect on the value of the original variable that was passed in.
If you instead pass in a variable ByRef, any changes you make to this variable also change it's value outside the routine. (Note: This is often considered bad practice because it makes code difficult to follow and even harder to understand.)
So you want an example huh? Take a look at the following piece of code.

---------
Dim iFirst, iSecond
iFirst = 1
iSecond = 2
' Call our Sub.

SwapValues iFirst, iSecond

' Both values are now 1!

Response.Write "First: " & iFirst &

Response.Write "Second: " & iSecond &

------------
Sub SwapValues(ByVal iFirst, ByRef iSecond)
Dim iTemp

iTemp = iFirst
iFirst = iSecond
iSecond = iTemp
End Sub

------------

' iSecond was changed because it was passed ByRef
' while iFirst was not since it was passed ByVal.
' In order to actually swap the values you'd need
' to make both parameters ByRef.

So which should you use? Well that depends! (How did you know I would say that?) The default is ByRef and for the most part that makes sense. Why use the additional memory to make a copy of the variable? When you're passing variables to components however, ByVal should really be the method of choice. It's much easier to just give the component a copy of the value then to have it need to worry about sending back any changes it might make to the variable. Imagine if this component was on a different computer and the point becomes clear pretty quickly. Every time a change was made to the value, the component would have to go back to the first computer to change the value!

Inga kommentarer: