Hi Alex,
The key to this question is remembering that a variable which holds an
object <doesn't> hold an object!! It holds a pointer, or reference, to the
object. Thus you have two separate pieces of memory intimately associated. If
you make a copy of an object variable you are creating a new reference to the
same associated object - whether you do it by assignment or as a ByVal
parameter.
Consider this class:
Class Foo
Private m_Bar As SomeCollection
Property Bar As SomeCollection
Set
Bar = Value
End Set
End Property
End Class
In use:
Dim oFoo As New Foo
Dim oCollectionOfStuff As New SomeCollection
oFoo.Bar = oCollectionOfStuff
The property oBar has now given oFoo.m_Bar a <copy> of oCollectionOfStuff
because Value is passed <ByVal>.
oCollectionOfStuff, however, holds a <reference> to an instance of
SomeCollection. So m_Bar holds a <copy of the reference>.
This means that there are there are now two references but still only a
single instance of SomeCollection. (There's no duplication of the contents of
the colection either.)
==========================
ByVal and ByRef in association with objects is the same, and yet not the
same, as ByVal and ByRef with ValueTypes, such as Ints, Structures, etc.
The similarity with ByVal is that <in both cases> it will pass a <copy> of
the variable.
The difference is that with ValueTypes, it's a copy of the actual data,
whereas for object types it's a copy of the <reference> and hence there's no
duplication of the object itself (just the referencing variable).
The similarity with ByRef is that <in both cases> it will pass a
<reference> to the variable.
The difference is that with ValueTypes, it's a refernce to the the actual
data, so changes to the variable within the method will produce changes in the
caller's variable.
But for object types it's a reference to the <reference> and changes to
the variable within the method will cause the caller's variable to point to a
different object. [The original object will remain unchanged, but may find
itself without anyone pointing to it, and will thus be ready for garbage
collection.]
Regards,
Fergus