Chapter 6 -- Object By Value

[Previous] [Next]

Chapter 6

A programmer new to object-oriented programming in Microsoft Visual Basic might assume that all that is required to pass an object by value is to include the ByVal reserved word in a function declaration. For example:

 Public Sub Foo(ByVal br As Bar) br.color = GREEN End Sub 

One could mistakenly infer that if the function caller passed in a Bar object that the Visual Basic compiler would create a copy of the object. The function code block could then manipulate the copy without affecting the original. For example:

 Dim myBar As Bar Set myBar = New Bar myBar.color = BLUE Call Foo(myBar) ' Question: Does myBar.color = BLUE? ' ' Answer: No. The value of myBar.color is GREEN. 

The value of myBar.color changes in the calling program because passing an object by value actually passes a reference to the object. For an explanation of this functionality, refer back to Chapter 2.

Another common misconception along the same lines is that if a class defines only a Property Get procedure to return an object and not a Property Set procedure, the class property is read-only. For example:

 ' ClassModule Foo ' Private m_Bar As Bar  Public Property Get TheBar() As Bar Set TheBar = m_Bar End Property 

One might then assume that the Visual Basic compiler will return a copy of the Bar object when the TheBar Property Get procedure is called, and whatever the caller does to it has no effect on the original. For example:

 Dim myFoo As Foo Dim myColor As Color Set myFoo = New Foo ' You can do this. myColor = myFoo.TheBar.Color ' Question: Can you do this? myFoo.TheBar.Color = PURPLE ' Answer: Yes, because a copy of the object reference to a Bar ' object is returned to the TheBar Property Get procedure, ' not a copy of the object itself. 

In both of the previous source code examples, a copy of an object reference is returned—not a copy of an object. To review the explanation provided in Chapter 2, an object variable in Visual Basic contains a reference to an object, not the object itself. Therefore, when an object variable is passed by value, a copy of the object variable is created that references the same object. Hence actions performed on all copies of an object variable affect the same object.

The Object By Value design pattern described in this chapter enables you to pass an object by value—passing a copy of the object rather than the object reference—by writing the object's state to a data stream, passing the data stream to the recipient process that constructs a copy of the object, and updating the new object's state from the data stream. This will produce an exact copy of the original object in the recipient process's address space.



Microsoft Visual Basic Design Patterns
Microsoft Visual Basic Design Patterns (Microsoft Professional Series)
ISBN: B00006L567
EAN: N/A
Year: 2000
Pages: 148

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net