Hacker’s Guide to Visual FoxPro
An irreverent look at how Visual FoxPro really works. Tells you the inside scoop on every command, function, property, event and method of Visual FoxPro.
COMPOBJ()
This function compares two objects and tells you if they’re identical. It does not tell you if they’re really the same object.
lMatch = COMPOBJ( oObject1, oObject2 )
Parameter |
Value |
Meaning |
oObject1 |
Object |
A reference to the first object to be compared. |
oObject2 |
Object |
A reference to the second object to be compared. |
lMatch |
.T. |
The two objects have the same list of properties and each property has the same value in the two objects. |
.F. |
The two objects do not completely match. |
This function confuses people. It takes two object references and compares the objects they point to. If the objects have exactly the same list of properties and the properties all have exactly the same values (the comparison is case-sensitive), the function returns .T.
So what’s the problem? Many people want to use COMPOBJ()
to see if two object variables point to the same object, but it only tells you if they don’t. That is, if COMPOBJ()
returns .F., you know you have two different objects, but if it returns .T., you don’t know one way or the other. In VFP 6 and later, checking whether two object references refer to the same object is as simple as comparing them with =, but in older versions, it’s trickier. The example demonstrates the problem with COMPOBJ()
, as well as showing the new and old ways to find out if you have two references to a single object.
* Create two forms
o1 = CREATEOBJECT("Form")
o2 = CREATEOBJECT("Form")
? COMPOBJ(o1, o2) && Returns .F. - No surprise since
&& their captions and names are different
? COMPOBJ(o1, o1) && Returns .T. - Again, no surprise
* Make another reference to o1
o3 = o1
? COMPOBJ(o1, o3) && Returns .T. - Good
* Now watch this
o2.Caption = o1.Caption
o2.Name = o1.Name
? COMPOBJ(o1, o2) && Surprise - Returns .T.
* So how do we find out if they point to the same object?
* In VFP 6 and later, do it like this:
? o1 = o2
* Thanks to Ken Levy for the basic idea here,
* useful in VFP 3 and VFP 5:
cHoldCaption = o1.Caption
o1.Caption = "XXX"
? COMPOBJ(o1, o3) && Still returns .T. - they're the same object
? COMPOBJ(o1, o2) && Returns .F. - they're different objects
o1.Caption = cHoldCaption
The trick in the older versions is to change a property of one object. If the other object changes, too, then they’re really references to the same object. If the other object doesn’t change, they’re references to different objects that happen to be identical. This test is a good candidate for a generalized black-box function.