Null Ref

Forums:

null reference pointer errorsNull Reference..bleh!
I just wanted to point this one out because recently I had fallen victim to this (somewhat rookie) mistake. Working on some code I had written quite a few years back I began receiving null object exceptions. Having more than 10k lines worth of code spanning multiple libraries it was not a simple find. The ask was a simple one, just add another object, but it was handled differently with slightly different properties available to consume. This is where my clock image comes in. A null reference exception does not necessarily mean that there is no object. It can also mean that you are trying to reference a property on an object that was never set, or null. Say you create a simple clock object containing two properties, hour and minute. Since it is only used for displaying the hour and minute and no time calculations you make them both simple strings. You instantiate a new clock object using clock myclock= new clock() Next you want to display the hour and minute somewhere using myclock.hour and myclock.minute. The problem lies if "minute" was late to join the party and never set on the object when you try to call it. {POOF} null object exception Handling this scenario is quite simple though. After you instantiate your object, simply set the two properties with empty strings or something like "minute not available". clock myclock=new clock(); myclock.hour=""; myclock.minute=""; The properties will not throw a null exception if they have been initialized. (Of course, not to say that you should not include other handling to determine why minute was late to the party.. late bus, traffic, hangover, etc) This includes any other properties like objects, integers, strings, lists, bools, etc ... ie. myObject.availableHours = new string[]{}; myObject.objList = new List<listobj>(){}; As long as they are set, you should not get an exception because you have defined the object as well as its properties, even if the properties have empty values. To note: Booleans are a bit trickier because they are only true or false which can lead to invalid answers so handle them with caution.