A good question on the discord server I participate in prompted a good question. It started with IS and = are just synonyms right?
It turns out that MOST times this may be true. But not always. And that little “but not always” can get you in trouble if you dont know when the difference is important.
IS is always used to determined if one instance of a class refers to the exact same instance as another reference. You might want to reread my prior post about classes, instances and objects
And in many cases, but not all, = will give you the same result as using IS.
So code like
Dim d1 As New Class2 Dim d2 As New Class2 If d1 = d2 Then System.debuglog "d1 = d2 => true !" Else System.debuglog "d1 = d2 => FALSE !" End If If d1 Is d2 Then System.debuglog "d1 IS d2 => true !" Else System.debuglog "d1 IS d2 => FAlSE !" End If
will usually put out debug log messages that say D1 = D2 => false from both checks.
This assumes that our class, Class2, does NOT implement operator_compare. And that is the caveat here. IF a class implements operator_compare the IS and = operators may not give the same result any longer.
Operator_compare is often used to compare the contents of a class – and not the references (although it doesnt have to compare contents since you can make it do whatever you want).
If we defined our class, Class2, like
Protected Class Class2 Sub Constructor(contents as string) myContent = contents End Sub Function Operator_Compare(rhs as Class1) As integer If rhs Is Nil Then Return -1 End If If Self.myContent < rhs.myContent Then Return -1 End If If Self.myContent > rhs.myContent Then Return 1 End If Return 0 End Function Private myContent As String End Class
Now our code above will give very different results because Operator_compare is used when the line
If d1 = d2 Then
is run. In this case it will call the custom operator_compare method and that compares the contents of two objects and NOT whether or not two objects references refer to the same object. However, the line
If d1 Is d2 Then
will ALWAYS determine if the two objects references refer to the same instance.
And now you know !