Just wanted to know if someone can explain the difference between these two conditionals:
if ( !object )
if ( object == null )
where object is an instance of a user-defined class.
I’m sure that these two cannot be used in an interchangeable manner, or are they?
Thanks.
The effect is in practice the same, so I guess you could say they’re interchangeable.
In a boolean context (such as a conditional), an expresion is evaluated to either true or false.
In Actionscript 3.0, the following values evaluate to false:
Everything else evaluates to true.
A reference to an user-defined class instance can either be null or not null.
So, in this case:
Obviously, the condition is met only if object is null.
In this other case:
The expression
objectwill evaluate to false ifobjectisnull. If it isnull, the expression is false. Since this is in turn negated, the final value will be true and so the condition will be satisfied. So, just like in the first case, ifobjectis null, the condition is met. And like in the first case, again, ifobjectis not null, the condition is not met.There’s no other option if your variable is typed to a user-defined class; such a variable can only contain a valid reference or null; i.e. it can’t hold any value evaluable to false in a boolean context, except for null; so, again, it’s either null or not null. Which is why both code samples have the same effect.