- Home /
Is there a difference between these null checks?
After reading this unity article about unity specific null checks I was wondering about shorthand null checks for unity objects. I never found a definitive answer on the forums or documentation so I decided to ask here. Is there a difference between:
if(_myObject)
and
if(_myObject != null)
and
if(!_myObject == null)
I know the last one doesn't make a lot of sense but I decided to add it for completeness sake. Will these ways of checking if a unity object is null always return the same values? Is there a difference in performance? Or are they exactly the same under the hood?
Answer by Hellium · Apr 22, 2021 at 01:07 PM
Here is the actual implementation of UnityEngine.Object
public static bool operator==(Object x, Object y) { return CompareBaseObjects(x, y); }
public static bool operator!=(Object x, Object y) { return !CompareBaseObjects(x, y); }
// Does the object exist?
public static implicit operator bool(Object exists)
{
return !CompareBaseObjects(exists, null);
}
static bool CompareBaseObjects(UnityEngine.Object lhs, UnityEngine.Object rhs)
{
bool lhsNull = ((object)lhs) == null;
bool rhsNull = ((object)rhs) == null;
if (rhsNull && lhsNull) return true;
if (rhsNull) return !IsNativeObjectAlive(lhs);
if (lhsNull) return !IsNativeObjectAlive(rhs);
return lhs.m_InstanceID == rhs.m_InstanceID;
}
As you can see:
• if(_myObject)
will call implicit operator bool
which basically checks whether _myObject
is null using CompareBaseObjects
• if(_myObject != null)
will call bool operator!=
which calls CompareBaseObjects
too
However, your last condition will "throw" a cs0472 warning since !_myObject
returns a bool, and comparing a bool against null
does not make sense.
So the third check would have to be if(!(_myObject == null))
for it to make sense?
Indeed. And it would be very similar to the 2nd example. You just invert the result returned by the overload of the ==
operator.
Note that Unity has a reference github repository with the source code of the UnityEngine dll. The bool type conversion operator and the two comparison operators can be found there.
Please keep in $$anonymous$$d that this repository is not open source. It's just there for reference. Make sure you read the license before extracting or using any code from there.
Your answer
Follow this Question
Related Questions
how can I check if an object is null? 4 Answers
what is null 1 Answer
XMLDocument GetElementByID returning null 1 Answer
Confused as to why I'm getting a NullReference Exception 1 Answer
Destroying an object not working 1 Answer