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.
' This sub look like it just swaps the values
' in the two variables, but does it?
Sub SwapValues(ByVal iFirst, ByRef iSecond)
iTemp = iFirst
iFirst = iSecond
iSecond = iTemp
' 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.
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!