views:

59

answers:

2

What VB6 method allows two custom objects of the same type (defined in a class module) to be compared to each other? I think there's an equivalent to Java's compareTo method, but I can't find it anywhere.

+2  A: 

If by "compare" you mean "are they the same type?", you can you the TypeName function:

If (object1 <> Nothing) and (object2 <> Nothing) then
  If (TypeName(object1) = TypeName(object2)) Then
    Debug.Print "object types are the same"
  Else
    Debug.Print "object types are NOT the same"
  End If
End If

If by "compare" you mean "do they reference the same object in memory?", you can use the Is operator:

If (object1 Is object2) Then
  Debug.Print "objects references are the same"
Else
  Debug.Print "objects references are NOT the same"
End If
raven
What I mean is that two instances of a class with identical attributes should return true. Naturally, you could compare those attributes manually, but I thought that VB6 had a method that you could define where that would happen automatically.
derekerdmann
Careful: object1 and object2 could be of different types but currently resolve to Nothing.
onedaywhen
@onedaywhen: Good catch. I assumed that TypeName returned the type of the object variable even if it was set to "Nothing", but instead it returns "Nothing". That complicates things. I put a check in my example code, but if one of those objects is Nothing, I guess a type comparison isn't possible.
raven
@derek: After reading the clarification you made in your comments, I now understand that I haven't answered your question. Sorry, I know of no method in VB6 that can do what you wish.
raven
Hey, don't sweat it. Thanks anyway!
derekerdmann
+1 There's no way to compare object instances by value. I don't think you can even compare structure instances.
MarkJ
No way besides serializing to byte array...
wqw
A: 

For others who may be wondering about the same question:

After doing a lot of looking around, it seems like VB6 doesn't have any kind of built-in compareTo or equals methods, like Java does.

I forgot that in Java, compareTo is defined in the java.lang.Comparable interface. Since interfaces are so broken in VB6, even if you wrote your own Comparable interface, you would have to call your object's Comparable_compareTo method unless it was declared as Comparable, which is pointless.

Bottom line: if you want compareTo or equals methods in your VB6 classes, just put them in.

derekerdmann