Often in code you might see checks for NIL written as
if foo = nil then
and sometimes you might see
if foo is nil
Whats the difference between the two ?
In Xojo the IS operator compares the references. It doesn’t compare the contents of the objects in any way. It answers the question “do these two references refer to the exact same instance” – in some languages this would be comparing whether two pointers point to the same location.
= will do much the same IF you have NOT implemented operator_compare for your specific classes. However if you HAVE implemented operator_compare then you can get VERY different results as your implementation of operator_compare will be called, even if one of the items is nil. In the following code
if foo = nil then
operator_compare for the instance foo would be called with the rhs parameter as NIL.
You can try this for yourself very quickly.
Create a new desktop project. In that new project add a Class named myClass. Add a method to myClass, Public operator_compare(rhs as myClass) as Integer
Simply put a break statement in the code
Now in Window1.open put
dim foo as new myClass
if foo = nil then // you will hit your break statement in the class
end if
if foo is nil then // you will NOT hit the break statement in the class
end if
The advice here is to be REALLY careful about when you use IS or =, or other comparison operators like >= <= <> etc, as they could mean VERY different things. And without reviewing code you can’t be sure whether a class does or does not have operator_compare implemented.
Use IS when you mean “are these the referring to the same instance”
Use the others when you _may_ mean something else.