<if you pass a value ByVal the original variable is not effected by anything that happens to the value you passed into the method. But if you pass a value in ByRef, it will be.
See, that's not quite true, and I can't tell if we don't agree or if we're miscommunicating. It's only true with respect to passing values to variables. It is NOT true when you pass references to variables. Whether passed ByRef or ByVal, a reference is still a reference.
If you take your above code and put a class as the argument instead of an integer:
Code:
public sub main
dim x as new myClass
dim y as new myClass
x.myProperty = 0
y.myProperty = 0
DoThingByVal(x)
DoThingByRef(y)
msgbox("X: " & x.myProperty & environment.newline & "Y: " & y.myProperty)
end sub
Public sub DoThingByVal(ByVal Value as myClass)
Value.myProperty += 1
end sub
Public sub DoThingByRef(ByRef Value as myClass)
Value.myProperty += 1
end sub
(also untested in .Net, tested in VB6)
When you run this, you will see a message box that says
Furthermore, all the books back up this point of view. Here's another quote (from Pattison: Building Applications and Components with VB.Net):
How does changing the parameter to a reference type affect what happens at runtime? Your intuition might tell you that you are passing a copy of the object by value because you have used the ByVal keyword. In reality, this is not what happens. The CLR creates a copy of the reference, not the object. Both the caller and the method have their own private copies of references that point to the same object. This the method sees the same object as the caller, and this method can make modifications to the object that can be seen by the caller.
So, I say an object reference passed ByVal works exactly like an object reference passsed ByRef, as far as behavior is concerned. The only difference is that in ByRef, each variable uses the same copy of the reference, and in ByVal, each variable gets its own copy of the reference.
As I said, I haven't been able to tell whether you agree with this or not--maybe you've been talking about stack variables all this time and I've been talking about heap references. So, what's your take on this?
I'm particularly curious to know how this plays out where strings are concerned, and why. In VB6, passing string arguments ByVal to an API call would allow the mod of the string for basically the same reason described in this quote.
Thanks,
Bob