Quantcast
Channel: Latest Questions by PokeJoe
Viewing all articles
Browse latest Browse all 20

Do I need to explicitly test for null or is testing the object itself good enough?

$
0
0
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?

Viewing all articles
Browse latest Browse all 20

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>