Null Reference Exceptions Should Not be Happening

Tags: C#

Null Reference Exceptions Should Not be Happening!  Errors like this - Object reference not set to an instance of an object - should never show up in your error logs.  These uninformative errors are preventable or at least easily replaced with something more informative.

Initialize Child Collections

Properties of objects that are collections or arrays should be initialized.  You can simply new up the collection in the object’s constructor.  If you do this as a rule you don’t have to worry about placing (or forgetting to place) null checks throughout your code every time you access the collection.  I've seen developers new up the collection inside the property getter as well.

Methods that Return Collections

It’s also a good practice in my book that methods that return collections should return empty collections rather than null. Again, this practice will eliminate a lot of pesky null reference exceptions.

Guard Clauses

Parameters passed into methods should be checked before trying to use them. If they are in an unexpected state, you can throw an informative error with a message referencing the property name. if (command == null) throw new ArgumentNullException("CreateOfferCommand");

These simple practices will eliminate many errors and make many others easier to troubleshoot.

No Comments

Add a Comment