Is there any reason to use if ( object != null ) in a conditional instead of the more concise if ( object ). I see the former more often, but it seems like the two are equivalent and the latter shorter.
Is there any reason to use if ( object != null ) in a
Share
The following code will have an object evaluate to
false, even though the object is not null:The
elseblock will execute in the example above, becausemyWrapperevaluates tofalse(itsvalueOfmethod returns whatever value the wrapper contained, in this casefalse) even thoughmyWrapperis not a null reference. The problem is that the above does not only test nullability of reference, it implicitly invokesvalueOfmethod, courtesy of Flash Player virtual machine. This behavior of course may or may not be what you wanted – do you want to test whethermyWrapperis a null value or whether it carries a null value? (or both perhaps).Verbosity in this case is your friend, otherwise you gain code readability in return for potential runtime errors.