Posts Tagged ‘Value’

Exceptions Explained: NullReferenceException

Sunday, November 8th, 2009

This is the first on a new series of posts that I’m going to be doing on explaining various different exceptions, what they mean, when you might get them and how to avoid them.

The first one is the NullReferenceException, which usually comes with the message “Object reference not set to an instance of an object.”. This Exception occurs when you try to access an object reference which is set to Nothing.

First of all, you need to understand the difference between value types and reference types in .NET. With a value type, we only care about what data is stored within it. With a reference type, the actual instance of the type is important in itself. For example, we may have an Integer, which contains 10. Integers are value types, and there is generally nothing particularly different between one number 10 and another number 10 if they are both Integers, so they are effectively identical.

Reference types on the other hand are different. If we have two customers, and both of them happen to be called “John Smith”, we don’t want to treat them as being the same thing just because they have the same name. The other difference with reference types is that we can have an empty reference – Nothing (or null in c#).

In fact, behind the scenes, reference types store a location in memory of the instance. In older programming languages, such as C/C++, these were known as pointers, and you could actually access them just like a number and change the item that they were pointing to with arithmetic operators (+/-/increment/decrement etc.) This created a number of potential problems and so references were created to protect pointers from causing too much damage. References also the garbage collector to keep track of what is referencing an object instance so that the instance can be cleared up when it is no longer in use.

The NullReferenceException is thrown when you attempt to access an object reference which is set to Nothing. This can easily happen because as mentioned above, all variables of a reference type will be initialised to Nothing by the .NET framework if they have not been explicity set to something else.

For example,

        Dim c As Customer
        c.Name = "John Smith"

The second line in the above piece of code will throw a NullReferenceException as the variable c is still set to Nothing, and when the .NET framework attempts to access the Name field, it will find that the object does not exist.

This is easily resolved by setting c to whatever Customer you wish to use, or to a New Customer.