Often I avoid NullReferenceExceptions by testing my objects before I use them like so:
if (obj) {
obj.property = 5;
}
Generally if the object is null, it won't pass the if (obj) test, and I avoid a NullReferenceException. Sometimes the above code causes an error that obj cannot be converted to bool, in which case I test it like this:
if (obj != null) {
obj.property = 5;
}
and this works fine. But barring this circumstance, is there a reason that I should avoid the first way of doing it? Also, why is it that it's sometimes fine to do it the first way, and other times causes an error?
↧