Hi Andy
Hopefully the following expansion of your example will illustrate the
difference.
Public Class CPerson
Public Name as String
Public Age as Integer
End Class
Public Sub ChangePerson1(ByVal Person as CPerson)
' These lines will always change Name and Age
Person.Name = "MyName"
Person.Age = 22
' The next line will have no effect on the caller
Person = New CPerson
End Sub
Public Sub ChangePerson2(ByRef Person as CPerson)
' These lines will always change Name and Age
Person.Name = "MyName"
Person.Age = 22
' This line will affect the caller
Person = New CPerson
End Sub
As you will see, the only difference between ChangePerson1 and ChangePerson2
is the ByVal / ByRef parameter.
In each case, the function is passed a CPerson object. In the first the
pointer to the object is passed by value, therefore it will not affect the
callers pointer to the object. In the second case the function is passed a
reference to this pointer. If you change it it will also change the caller's
pointer.
In essence, the object is always passed by reference (in a pointer) but the
pointer is the thing that is affected. The reason for this is that if the
entire object were passed by value then the function call would have to
perform a byte-by-byte copy of the object, and this could be a very costly
overhead for large objects.
HTH
Charles
"Andy Read" <qz****@btinternet.com> wrote in message
news:bi**********@hercules.btinternet.com...
Dear all,
I thought I understood passing parameters ByVal and ByRef but I
clearly don't! If I define a simple class
of:
Public Class Person
Public Name as String
Public Age as Integer
End Class
Then pass a person object to a method 'ByVal'
Public Sub ChangePerson(ByVal Person as Person)
Person.Name = "MyName"
Person.Age = 22
End Sub
Why are the values Name and Age changed when I'm passing by value? I
would expect this behaviour when I'm passing by reference. I'm confused...(It's
not difficult!)
Any pointers to set me straight would be appreciated!
Thanks